我在这里发帖是因为我需要你的帮助来解决这个问题。我一直在尝试自己修复它,但我没有运气。我真的不明白发生了什么。如果您查看我的代码,您会注意到我有以下循环:
for (j = 0; j < total_scores; j++)
{
cout << "P is " << p << endl ;
cout << "Enter score : ";
cin >> scores[p];
p++;
}
好吧,如果我启用这段代码,存储名称的数组就会损坏,我会得到位置 0 的奇怪结果:4@ 和一个错误“Run-Time Check Failure #2 - Stack around the变量‘scores’已损坏。”
我真的不明白为什么,或者如何解决这个问题。没有要求分数的循环,带有名称的循环保持不变。如果它们是两个独立的元素,我不明白这里发生了什么。
有什么想法吗?非常感谢您的时间和关注。
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int total_students= 2 ;
const int scores_students = 1 ;
const int total_scores = scores_students*total_students;
string names[total_students];
double scores[total_scores];
double average[scores_students];
double averages=0.0;
int i;
int j = 0 ;
int k;
int l;
int m;
int p = 0 ;
for (i = 0; i < total_students; i++)
{
cout << "I is " << i << endl;
cout << "Enter name : ";
cin >> names[i];
for (j = 0; j < total_scores; j++)
{
cout << "P is " << p << endl ;
cout << "Enter score : ";
cin >> scores[p];
p++;
}
}
for (m = 0 ; m < total_students ; m++)
{
cout << "\nName : " << names[m] << endl << endl ;
//cout << "Average : " << average[m] << endl;
}
system("pause");
system("pause");
}
我需要的是询问姓名的程序,然后是基于“scores_students”的测试结果,然后是第二个名字和下一个分数。等等
我正在寻找的输入示例:
Name Score1
Peter 20
Mark 100
最佳答案
你在一个循环中有一个循环,所以 p
最终会增加到 4,因此您尝试访问 scores[4]
当数组大小仅为 2 时。
根据评论,看起来答案是“j 循环”应该是 for (j = 0; j < scores_student; j++)
而不是 total_scores
这导致了上面提到的溢出。
关于c++ - 为什么这个循环会破坏数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26879055/