我想从我的输入文件中读取数据
70 95 62 88 90 85 75 79 50 80 82 88 81 93 75 78 62 55 89 94 73 82
并将每个值存储在一个数组中。这个特殊问题还有更多(其他功能现在被注释掉了),但这才是真正给我带来麻烦的地方。我在上一个关于数据和数组的问题上看了几个小时,但我找不到我在哪里犯了错误。
这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int SIZE = 22;
int grades[SIZE];
void readData() {
int i = 0;
int grades[i];
string inFileName = "grades.txt";
ifstream inFile;
inFile.open(inFileName.c_str());
if (inFile.is_open())
{
for (i = 0; i < SIZE; i++)
{
inFile >> grades[i];
cout << grades[i] << " ";
}
inFile.close(); // CLose input file
}
else { //Error message
cerr << "Can't find input file " << inFileName << endl;
}
}
/*
double getAverage() {
return 0;
}
void printGradesTable() {
}
void printGradesInRow() {
}
void min () {
int pos = 0;
int minimum = grades[pos];
cout << "Minimum " << minimum << " at position " << pos << endl;
}
void max () {
int pos = 0;
int maximum = grades[pos];
cout << "Maximum " << maximum << " at position " << pos << endl;
}
void sort() {
}
*/
int main ()
{
readData();
return 0;
}
这是我的输出:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
感谢您的时间。
原文由 dev_P 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题是您要声明一个大小为 1 的本地
grades
数组,隐藏全局grades
数组。不仅如此,您现在正在访问超出范围的数组,因为本地grades
数组只能容纳 1 个项目。所以摆脱这条线:
但是,需要指出的是:
不是有效的 C++ 语法。您只是错误地偶然发现了这一点,但如果使用严格的 ANSI C++ 编译器编译该代码将无法编译。
C++ 中的数组必须使用常量表达式声明,以表示数组中的条目数,而不是变量。您无意中使用了一个非标准的编译器扩展,称为 可变长度数组 或简称 VLA。
如果这是为了学校作业,请不要以这种方式声明数组(即使您打算这样做),因为它不是正式的 C++。如果你想声明一个动态数组,这就是
std::vector
的用途。