[英]While iterating through a string, why am I NOT getting out of range error, even though I'm already beyond its length?
My code is literally this: 我的代码从字面上是这样的:
int main(){
string s = "Success!\n";
for (int i=0; i<10; ++i) cout<<s[i];
return 0;
}
string s is of length 8; 字符串s的长度为8; and even though I've used an iterator 'i' that goes beyond the string's length, I do not get any error.
即使我使用的迭代器'i'超出了字符串的长度,也没有出现任何错误。 Why?
为什么? Output is:
输出为:
Success!
WITH A NEWLINE, I have not even put a newline character 有了换行符,我什至没有放换行符
string s is of length 8
字符串s的长度为8
no it's not, it's 9. 不,不是9。
and even though I've used an iterator 'i' that goes beyond the string's length, I do not get any error
即使我使用的迭代器“ i”超出了字符串的长度,也没有出现任何错误
You're not going beyond the string's length, you go equal to the string's length. 您不会超出字符串的长度,而是等于字符串的长度。 This is defined as returning a null character.
定义为返回空字符。 Even if you went beyond the string's length with
operator[]
, this is undefined behavior , not expected to throw an exception. 即使使用
operator[]
超出了字符串的长度,这也是未定义的行为 ,不希望引发异常。
I have not even put a newline character
我什至没有放换行符
... yes you did. ... 是的,你做到了。
As per the definition of subscripting (bracket) operator for string : 按照字符串的下标(括号)运算符的定义:
char& operator[] (size_t pos);
char&运算符[](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).
如果pos等于字符串长度,则该函数将返回对字符串中最后一个字符之后的空字符的引用(不应修改)。
"Success!\\n"
is a string of length 9. With S
at index 0, !
"Success!\\n"
是长度为9的字符串S
的索引为0 , !
at index 7, and \\n
at index 8. So when you reference s[9], it's returning back the null \\0
char. 在索引7处为
\\n
在索引8处为\\n
。因此,当您引用s [9]时,它将返回空\\0
char。
代替cout << s[i]
使用cout << s.at(i)
,您将获得所需的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.