substring() 抛出未经处理的异常

substring() throwing Unhandled Exception

本文关键字:处理 异常 substring      更新时间:2023-10-16

我正在尝试制作一个简单的程序来帮助用户快速学习打字。它打印一个字符,用户应该快速按下它以"获胜"。

我收到运行时错误:

在"学习快速键入"中0x772A33D2处发生未经处理的异常.exe:Microsoft C++异常:在内存位置0x00FEF138发生 std::out_of_range。

这是我的代码:

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string.h>
using namespace std;
int main()
{
    srand((unsigned)time(NULL));
    while (true)
    {
        int r = rand() % 26;
        string length = "abcdefghijklmnopqrstuvwxyz";
        size_t found = r;
        size_t sz = 1;
        string sub = length.substr(length.at(found),sz);
        cout << sub << endl;
    }
}

std::string::substr()索引作为输入,但您传递的是从给定索引检索到的字符。 该字符的值被误解为索引,并且字符串中的所有字符的数值 (97..122( 都高于字符串的size() (26(,因此substr()引发std::out_of_range异常:

异常

std::out_of_range如果pos > size()

调用 substr() 时,您需要将length.at(found)替换为 found

//string sub = length.substr(length.at(found),sz);
string sub = length.substr(found,sz);