从文件中读取行时出错

Error when reading lines from file

本文关键字:出错 读取 文件      更新时间:2023-10-16

如果这个问题已经得到回答,我深表歉意,我尝试搜索,但无法弄清楚为什么这不起作用。

我正在编写一个程序来从文件中读取,该文件包含一个名称的行,后跟 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

我使用了getline函数和一个字符串流

使用 getline 更容易处理,因为您可以在字符串中写入 并修改或分析此字符串

字符串流是从字符串中提取数据的一种很酷的方法

这是我要怎么做的

you have to include sstream
string line{""};
if (inFile.is_open()) {
while (getline(inFile,line)){
names[students] = line.substr(0, line.find(" "));
stringstream ss;
ss << line.substr(line.find(" "));
for(size_t i{0}; i < 5; ++i){
ss >> dec >> test[students][i];
}  
++students;
}
inFile.close();  
} else {
cout << "could not read file";
}