首页 > 解决方案 > 如何修复“for”循环并没有停止

问题描述

我正在制作一个int被调用的数组,scorefor循环不能正常工作(我认为循环没有停止)。

我试图删除cin >> score[i]它并恢复正常。

array<int, 9> score;

cout << "Score graphics from 1 to ten\n\n";

for(int i = 0; i <= score.size(); i++){
    cout << "The number of people who get " << i + 1 << " : ";
    cin >> score[i];
}

The number of people who get 1 : (input)我希望输出The number of people who get 10 : (input)

标签: c++arrays

解决方案


这个:

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

应该:

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

由于score.size()将返回9,但数组的最后一个索引是8.

 

使用您的原始代码,当访问索引过大的数组时,循环的最后一次运行只会调用一些未定义的行为:

cin >> score[9];  // score array only goes from 0 to 8!!

推荐阅读