c++ - 将像 Strlen C++ 一样工作的函数

标签 c++ strlen

我想创建一个与 Strlen 功能相同的函数,但出现错误:“字符串下标超出范围”。我尝试修复它但不知道。

代码如下:

#include "stdafx.h"
#include "stdafx.h"
#include <string>
#include <sstream>
#include <iostream>


using namespace std;

int strlen1( string str)
{
    int count=0;
    int i=0;
    while (str[i]!='\0')
        {
            count++;
            i++;
    }
    return count;
}

int _tmain(int argc, _TCHAR* argv[])
{
    string input;
    cin >> input;
    cout << strlen1(input) << endl;

    return 0;
}

谢谢!

最佳答案

简而言之,对于非 const std::string访问超出字符串长度的元素具有未定义的行为(更准确地说,当为此使用非 const operator[] 时)。

C++98 §21.3.4/1,关于 std::string::operator[] :

If pos < size, returns data()[pos]. Otherwise, if pos == size(), the const version returns charT(). Otherwise the behavior is undefined.

并且您的字符串是非 const .

你可以做到const ,然后将调用标准中的一项特殊规定,保证元素 n 的结果为零,但这并没有解决您的函数对于 std::string 完全多余的问题。 .

也许你的意思是参数类型 char const* .

那会更有意义,然后该函数也可以工作。

干杯,

关于c++ - 将像 Strlen C++ 一样工作的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4890734/

相关文章:

C++ CreateProcess() 在与第一个相同的窗口中运行

c++如何创建写入xml以及如何从中读取?

c++ - 从 ScriptManager(javascript) 获取返回文本 - INDESIGN SDK 插件

c++ - 迭代器类型中使用的 vector 元素类型

php - 我的 jQuery 和 PHP 对同一件事给出不同的结果?

c - 在c中获取字符串长度的问题

c++ - 先前关闭的文件句柄上 fclose() 的双重释放错误

c++ - 在 C++ 4.8.1 中使用 strlen 的打印输出时出现段错误

PHP strlen() 函数在 Enterkey 计数中的异常行为

c - 为什么 (positive_integer < negative_integer) 被评估为 true?