1
如果已经得到回答,我表示歉意,我试着搜索并找不到为什么这不起作用。从文件中读取行时出错
我正在编写一个程序来读取文件,该文件包含一个名称后跟5个整数的行。我试图将名称读入一个字符串数组,然后将5个整数读入另一个数组中。当我运行我的代码时,第一个名字和前5个整数按预期读取,但是当循环继续时,没有其他任何内容被读入数组中。
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int row, col, average, students = 0;
string storage;
string names[15];
double test[15][5];
double grade[15];
ifstream inFile;
ofstream outFile;
inFile.open("testScores.txt");
outFile.open("averages.out");
for (students; !inFile.eof(); students++)
{
//getline(inFile, storage, '\n');
inFile >> names[students];
for (col = 0; col <= 5; col++)
{
inFile >> test[students][col];
}
inFile.ignore('\n');
}
我知道使用命名空间std是皱眉,但这是我的老师希望我们完成代码的方式。我尝试添加一个忽略来跳到输入中的下一行,但这似乎没有奏效。我也尝试使用getline使用临时存储字符串,但不确定这是最好的方式去做。任何帮助将不胜感激。谢谢
输入文件 -
Johnson 85 83 77 91 76
Aniston 80 90 95 93 48
Cooper 78 81 11 90 73
Gupta 92 83 30 69 87
Blair 23 45 96 38 59
Clark 60 85 45 39 67
Kennedy 77 31 52 74 83
Bronson 93 94 89 77 97
Sunny 79 85 28 93 82
Smith 85 72 49 75 63
阅读本https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong然后告诉我们您的输入文件是什么样子。这和其他许多重复的内容也可能相同。 https://stackoverflow.com/questions/1744665/need-help-with-getline –
它是col <= 5'还是col <5'? – iBug
@iBug我猜这也是问题,但没有输入文件,这只是一个猜测。但是,是的,试图将一个字母读入一个数字会导致错误,并且由于没有错误检查,所以不会被注意到,而其他所有读取都会失败。 –