substring() 抛出未经处理的异常
substring() throwing Unhandled Exception
我正在尝试制作一个简单的程序来帮助用户快速学习打字。它打印一个字符,用户应该快速按下它以"获胜"。
我收到运行时错误:
在"学习快速键入"中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);
相关文章:
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 有没有更好的方法来处理异常? try-catch块真的很丑
- VisualC++ 2010 有没有办法找出有关未处理异常错误的更多详细信息
- 在析构函数内部处理异常(但不抛出)
- C++ 程序中双链表的未处理异常
- 抛出字符但捕获整数:如何处理异常的促销和转化
- C++ 异常处理:异常与 ifstream::failure
- 防止线程在处理异常后在分离时调用 std::terminate()
- 当数字可能超出C++中特定数据类型的范围时如何处理异常?
- 运算符重载时未处理<<异常
- 实验室中0x6BE20E11 (ucrtbased.dll) 的未处理异常.exe: 0xC0000005:访问冲突读取
- objective-C或ObjectiveC++能处理C++异常吗
- 如何处理异常,使我的程序仍然运行
- ImageMagick 的未处理异常
- 类数组大小为的未处理异常
- 尝试将构造函数设置为 0 - c++ 的未处理异常
- C - 处理异常而不会丢失呼叫箱
- 在分配scoped_ptr之前处理异常
- C++异常处理如何处理异常派生类
- Dijkstra 中0x001e1078 s_Algorithm.exe的未处理异常:0xC0000005:访问冲突读取位置0xbaadf00d