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; and even though I've used an iterator 'i' that goes beyond the string's length, I do not get any error. Why? Output is:
Success!
WITH A NEWLINE, I have not even put a newline character
string s is of length 8
no it's not, it's 9.
and even though I've used an iterator 'i' that goes beyond the string's length, I do not get any error
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.
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);
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"
is a string of length 9. With S
at index 0, !
at index 7, and \\n
at index 8. So when you reference s[9], it's returning back the null \\0
char.
代替cout << s[i]
使用cout << s.at(i)
,您将获得所需的结果。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.