英文:
Issue when writing a simple code using for loops
问题
这是错误:
在 Project1.exe 中的 0x00007FFD16B7FE7C 处发生未处理的异常: 内存位置 0x0000000B2FAFF760 处的 Microsoft C++ 异常: std::out_of_range。
这是代码:
#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;
}
请问有其他需要吗?
英文:
this is the error :
Unhandled exception at 0x00007FFD16B7FE7C in Project1.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0000000B2FAFF760.
here is the code :
#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;
}
im also still not sure where the code breaks it, it just takes me to a weird window with A LOT OF LINES that i have no idea what they mean.
i tried debugging, rebuilding, trying some alternative ways to write the code that i know of and nothing worked, like the code is so simple HOW AM I OUT OF MEMORY XD.
答案1
得分: 3
在这个for循环中,
for (int i = 0; i <= word.size(); i++)
cout << word.at(i) << endl;
变量i
的范围是[0, word.size()]
。然而,成员函数at
在其参数等于或大于成员函数size()
返回的值时会抛出out_of_range
异常。
因此,修改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;
英文:
In this for loop
for (int i = 0; i <= word.size(); i++)
cout << word.at(i) << endl;
the variable i
is being changed in the range [0. word.size()]
. However the member function at
throws exception out_of_range
when its argument is equal to or greater than the value returned by the member function size()
.
So change the for loop like
for (int i = 0; i < word.size(); i++)
cout << word.at(i) << endl;
Pay attention to that opposite to the member function at
the index of the subscript operator may be equal to the value of size()
.
That is you may write
for (int i = 0; i <= word.size(); i++)
cout << word[i] << endl;
though there is no great sense to use the index equal to the value of size().
To avoid such a mistake it is better to use range-based for loop like
for ( char c : word )
cout << c << endl;
or
for ( const auto &c : word )
cout << c << endl;
答案2
得分: 1
尝试使用:
for (int i = 0; i < word.size(); i++)
如果word
中有size
个元素,循环将运行size
次,而不是size + 1
次。
英文:
Try with:
for (int i = 0; i < word.size(); i++)
If you have size
elements in word
, the loop will run size
times, not size + 1
times.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论