gpt4 book ai didi

c++ - 字符串超出范围c++

转载 作者:搜寻专家 更新时间:2023-10-31 00:13:48 25 4
gpt4 key购买 nike

当我尝试检查 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);
  1. Requires: pos <= size()

  2. Returns: *(begin() + pos) if pos < size(). Otherwise, returns a reference to an object of type charT with value charT(), where modifying the object leads to undefined behavior.

  3. Throws: Nothing.

也就是只要pos <= size()满足条件,该方法永远不会抛出异常,否则行为是未定义,抛出异常就是其中一个例子。

关于c++ - 字符串超出范围c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25687891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com