从文件中读取行时出错
Error when reading lines from file
如果这个问题已经得到回答,我深表歉意,我尝试搜索,但无法弄清楚为什么这不起作用。
我正在编写一个程序来从文件中读取,该文件包含一个名称的行,后跟 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";
}
相关文章:
- 读取文件的最后一行并输入到链接列表时出错
- 从人员矢量插入和读取文件时出错
- 使用 Visual Studio 代码读取 C++ 中的输入流时出错
- 在C++中使用istringstream读取输入时出错
- 读取字符串C++的字符时出错
- 读取字符串字符时出错 - 对于数组中的字符串值
- 从文件中读取行时出错
- 将 Git 提交哈希读取到C++时出错
- 读取字符串字符时出错
- C++ 使用 Strtok 读取字符串字符时出错
- C++:使用 fgets() 读取字符输入时出错
- 使用 C++Builder 项目读取字符串中的文件时出错
- C ++ ifstream 无法读取字符串,并且在读取字符时出错
- 通过具有矢量基址的指针读取矢量元素时出错
- 尝试重复读取输入会出错
- 从字符串中读取字符时出错
- 分段 追加和读取二进制文件时出错
- 通过提升从流中读取 XML 时出错
- 使用 ifstream 读取文件时出错
- 为什么我在尝试从istringstream读取数据时出错