[英]Function that will act like an Strlen C++
我想制作一個功能與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
訪問超出字符串長度的元素具有未定義的行為(更確切地說,當使用non- const
operator[]
)。
C ++ 98§21.3.4/ 1 ,關於std::string::operator[]
:
如果
pos < size
,則返回data()[pos]
。 否則,如果pos == size()
,則const
版本返回charT()
。 否則,行為是不確定的。
而且您的字符串是非const
。
您可以將其設置為const
,然后將在標准中調用特殊規定以保證元素n的結果為零,但不能解決函數對std::string
完全冗余的問題。
也許您的意思是擁有參數類型char const*
。
那會更有意義,然后該功能也將起作用。
干杯,……
您似乎誤以為std :: string與C樣式的字符串(char const *)相同。 這是不正確的。 沒有空終止符。
這是您的strlen函數唯一起作用的方式:
int strlen1(string str) { return static_cast<int>(str.size()); }
std::string
為此具有不錯的size()
方法。
strlen基於零終止字符串(char *或char數組), C ++字符串基於長度+數據,您不能在字符串結尾(終端為零)之后訪問數據。 除此之外,獲取長度是C ++字符串(size())的標准屬性,因此寫strlen的標准方法只是調用size。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.