当我尝试检查 str[index]
是否等于时出现异常 String out of range
std::string Test::getTheText(std::string str) {
int index = 7;
string text;
cout << str[index] << endl; // Work!!
while (str[index] != '\"') // Exception,why?? also try while(str[index]!=34)
text += str[index++];
return text;
}
我的字符串是:文本 - bla bla
最佳答案
Why the below code works?
std::string str = "bla bla"; int index = 7; cout << str[index] << endl; // Work!!
如果index
等于字符串的长度(在您的例子中是 它是, 7 == strlen("bla bla")
),访问运算符返回对默认值 charT
的引用在 std::basic_string<charT>
实例化,对于 char
它是 \0
).
C++ string::operator[] reference
If pos is not greater than the string length, the function never throws exceptions (no-throw guarantee).
但是,稍后您尝试访问另一个元素:
str[index++] // in second iteration, the first is ok though
只有这样你才会陷入:
[...], it causes undefined behavior.
C++ 标准引用:
§ 21.4.5 basic_string element access [string.access]
const_reference operator[](size_type pos) const; reference operator[](size_type pos);
Requires:
pos <= size()
Returns:
*(begin() + pos)
ifpos < size()
. Otherwise, returns a reference to an object of typecharT
with valuecharT()
, where modifying the object leads to undefined behavior.Throws: Nothing.
也就是只要pos <= size()
满足条件,该方法永远不会抛出异常,否则行为是未定义,抛出异常就是其中一个例子。
关于c++ - 字符串超出范围c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25687891/