在遍历字符串时,为什么我没有出现超出范围的错误,即使我已经超出了它的长度?
While iterating through a string, why am I NOT getting out of range error, even though I'm already beyond its length?
我的代码实际上是这样的:
int main(){
string s = "Success!\n";
for (int i=0; i<10; ++i) cout<<s[i];
return 0;
}
字符串s的长度为8;即使我使用了超出字符串长度的迭代器 'i',我也没有收到任何错误。为什么?
输出为:
Success!
WITH A NEWLINE,我什至没有放一个换行符
使用 cout << s.at(i)
而不是 cout << s[i]
,您会得到想要的结果。
string s is of length 8
不,不是,是 9。
and even though I've used an iterator 'i' that goes beyond the string's length, I do not get any error
您不会超出字符串的长度,您会等于 字符串的长度。这被定义为返回空字符。即使您使用 operator[]
超出了字符串的长度,这也是 未定义的行为 ,预计不会引发异常。
I have not even put a newline character
...是的,你做到了。
根据subscripting (bracket) operator for string的定义:
char& operator[] (size_t pos);
If pos is equal to the string length, the function returns a reference to the null character that follows the last character in the string (which should not be modified).
"Success!\n"
是一个长度为 9 的字符串。S
在索引 0,!
在索引 7,\n
在索引 8。所以当你引用s[9],它返回空 [=14=]
字符。
我的代码实际上是这样的:
int main(){
string s = "Success!\n";
for (int i=0; i<10; ++i) cout<<s[i];
return 0;
}
字符串s的长度为8;即使我使用了超出字符串长度的迭代器 'i',我也没有收到任何错误。为什么? 输出为:
Success!
WITH A NEWLINE,我什至没有放一个换行符
使用 cout << s.at(i)
而不是 cout << s[i]
,您会得到想要的结果。
string s is of length 8
不,不是,是 9。
and even though I've used an iterator 'i' that goes beyond the string's length, I do not get any error
您不会超出字符串的长度,您会等于 字符串的长度。这被定义为返回空字符。即使您使用 operator[]
超出了字符串的长度,这也是 未定义的行为 ,预计不会引发异常。
I have not even put a newline character
...是的,你做到了。
根据subscripting (bracket) operator for string的定义:
char& operator[] (size_t pos);
If pos is equal to the string length, the function returns a reference to the null character that follows the last character in the string (which should not be modified).
"Success!\n"
是一个长度为 9 的字符串。S
在索引 0,!
在索引 7,\n
在索引 8。所以当你引用s[9],它返回空 [=14=]
字符。