c++ - 如何修复“for”循环并没有停止
问题描述
我正在制作一个int
被调用的数组,score
但for
循环不能正常工作(我认为循环没有停止)。
我试图删除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)
解决方案
这个:
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!!
推荐阅读
- mysql - SELECT inner Join Group by sub query extract in a single row
- javascript - ES6 和类型定义:动态地将类型分配给超类的属性和智能感知
- python - 从列表的文本文件列表到 Python pandas 数据框
- c++ - 在 C++ 中停止/终止在标准输入上等待的线程的干净方法
- angular - 使用角度/打字稿中的另一个函数为接口属性赋值?
- unity3d - 我们如何训练 tesseract(4.1 版)以获取额外的特殊字符(如除法符号“÷”)
- python - Django:重复检查失败
- angular - 在 TypeScript 中使用 Cypress 测试 Angular 时不会出现“sourceType:模块”错误
- python - 使用 gpu 的 stanfordnlp 将 python 代码容器化
- python - 如何使用python脚本将文件中的字符串值替换为字典键值