这是错误:
Unhandled exception at 0x00007FFD16B7FE7C in Project1.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0000000B2FAFF760.
这是代码:
#include <iostream>
using namespace std;
int main() {
string word;
cin >> word;
cout << word.size() << endl;
for (int i = 0; i <= word.size(); i++)
cout << word.at(i) << endl;
return 0;
}
我仍然不确定代码在哪里中断它,它只是把我带到一个奇怪的窗口,上面有很多行,我不知道它们是什么意思。
我尝试调试、重建、尝试一些替代方法来编写我知道的代码,但没有任何效果,就像代码是如此简单我怎么会内存不足 XD。
尝试:
for (int i = 0; i < word.size(); i++)
如果
size
中有word
元素,循环将运行size
次,而不是size + 1
次。
在这个for循环中
for (int i = 0; i <= word.size(); i++)
cout << word.at(i) << endl;
变量
i
在[0. word.size()]
范围内变化。然而,当成员函数at
的参数等于或大于成员函数out_of_range
的返回值时,它会抛出异常size()
。
所以像这样改变for循环
for (int i = 0; i < word.size(); i++)
cout << word.at(i) << endl;
注意与成员函数
at
相反的下标运算符的索引可能等于size()
的值。
那是你可以写的
for (int i = 0; i <= word.size(); i++)
cout << word[i] << endl;
尽管使用等于 size() 值的索引没有什么意义。
为避免此类错误,最好使用基于范围的 for 循环,例如
for ( char c : word )
cout << c << endl;
或
for ( const auto &c : word )
cout << c << endl;