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

标签 c++

当我尝试检查 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/

相关文章:

c# - 我怎样才能制作一个可以在没有其他安装的Windows上运行的exe

c++ - 快速计算 n 次 10 的负 m 次方

c++ - 删除指针问题

c++ - 使用 OpenGL 使用 C++ 制作 3D 橱柜图像

c++ - 如何创建彩条(电视测试图案)

c++ - 基类到派生类的类型转换

C++ 类构造函数清除映射

c++ - 主线程等待分离线程在 C++ 中完成?

C++:我如何从这段代码制作这个形状?

c++ - 如何以 Visual C++ 形式创建 InputTextBox