使用for循环编写简单代码时出现问题[关闭]

问题描述 投票:0回答:2

这是错误:

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。

c++ for-loop error-handling unhandled-exception
2个回答
1
投票

尝试:

for (int i = 0; i < word.size(); i++)

如果

size
中有
word
元素,循环将运行
size
次,而不是
size + 1
次。


0
投票

在这个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;
© www.soinside.com 2019 - 2024. All rights reserved.