我想创建一个与 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
, returnsdata()[pos]
. Otherwise, ifpos == size()
, theconst
version returnscharT()
. Otherwise the behavior is undefined.
并且您的字符串是非 const
.
你可以做到const
,然后将调用标准中的一项特殊规定,保证元素 n 的结果为零,但这并没有解决您的函数对于 std::string
完全多余的问题。 .
也许你的意思是参数类型 char const*
.
那会更有意义,然后该函数也可以工作。
干杯,
关于c++ - 将像 Strlen C++ 一样工作的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4890734/