[英]Read data from a file into an array - C++
我想从输入文件中读取数据
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
感谢您的时间。
我在读取文件时没有发现任何问题,您只是混淆了全局变量和局部变量的等级
你不需要这个
int i = 0;
int grades[];
在函数readData中
#include <string>
using namespace std;
const int SIZE = 22;
int grades[SIZE];
void readData() {
string inFileName = "grades.txt";
ifstream inFile;
inFile.open(inFileName.c_str());
if (inFile.is_open())
{
for (int 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;
}
}
int main()
{
readData();
return 0;
}
问题是您要声明一个大小为1的本地grades
数组,从而隐藏了全局grades
数组。 不仅如此,您现在还无法访问该数组,因为本地grades
数组只能容纳1个项目。
所以摆脱这一行:
int grades[i];
但是,需要指出的是:
int i = 0;
int grades[i];
不是有效的C ++语法。 您只是偶然发现了这个错误,但是如果使用严格的ANSI C ++编译器进行编译,该代码将无法编译。
必须使用常量表达式声明C ++中的数组,以表示数组中的条目数,而不是变量。 偶然地,您使用的是非标准的编译器扩展,简称为“ 可变长度数组”或VLA。
如果这是用于学校作业,则不要以这种方式声明数组(即使您打算这样做),因为它不是正式的C ++。 如果要声明动态数组,那就是std::vector
目的。
大小为22的原始原始全局数组grades
将被具有相同名称但大小为0的本地数组替换。
(它不会被覆盖,只有任何使用变量grades
代码(在第二grades
代码定义的范围内)将读取第二grades
组的值,因为它具有更高的优先级。)
inFile >> grades[i];
和cout << grades[i] << " ";
当您读取的错误超出其大小时,应该返回运行时错误(似乎您未使用严格的编译器)。
[ int grades[i];
通常会返回编译时错误,因为您不应该/通常无法使用变量初始化固定数组]
我认为发生的是, grades[i]
只是返回值为0的变量的匿名实例,而不是您的程序崩溃,因此是您的输出。
解决您的问题的最简单方法就是删除int grades[i]
。
(还删除int i = 0
之一,因为您不需要两次定义它)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.