【发布时间】:2021-02-10 17:38:36
【问题描述】:
测试文件
11111,Smith,Bob,10,9,8,10,9,10,92,89,90
11112,Doe,Jean,8,9,8,7,9,9,84,88,89
11113,Hardy,Joe,9,9,10,9,8,9,88,90,95
信息存储在
struct Student {
std::string ID;
std::string lName;
std::string fName;
int quiz1;
int quiz2;
int quiz3;
int quiz4;
int quiz5;
int quiz6;
int test1;
int test2;
int final;
float total;
};
问题:添加成绩时,它只会正确读取一年级。 我尝试了许多不同的方法,但这是迄今为止唯一一种甚至部分有效的方法:( 当手动设置学生结构时,测试值确实可以正常工作;所以读入的文件是问题
int main() {
//add a place to store student info
StudentGrades session;
string inFile = "classGrades.txt";
//open input file if possible or display an error message and exit with failure
ifstream in;
cout << "Opening File: " << inFile << "\n";
in.open(inFile);
if (in.is_open()) {
cout << "File Open: " << inFile << "\n";
string line;
while (getline(in,line)) {
//read in student info from file line by line to a Student object for each line
Student student;
std::stringstream stream(line); //record info from file
getline(stream,student.ID,',');
getline(stream,student.lName,',');
getline(stream,student.fName,',');
stream >> student.quiz1;
stream >> student.quiz2;
stream >> student.quiz3;
stream >> student.quiz4;
stream >> student.quiz5;
stream >> student.quiz6;
stream >> student.test1;
stream >> student.test2;
stream >> student.final;
session.add(student);
}
}
else
{
cout << "File could not be opened: " << inFile << "\n";
exit(1);
}
//close the input file
cout << "Closing File: " << inFile << "\n";
in.close();
cout << "File Closed: " << inFile << "\n";
session.printStudentList(cout);
return 0;
}
文件输出
Opening File: classGrades.txt
File Open: classGrades.txt
Closing File: classGrades.txt
File Closed: classGrades.txt
ID | Last Name | First Name | Q1 | Q2 | Q3 | Q4 | Q5 | Q6 | T1 | T2 | Final | Total
11113 | Hardy | Joe | 9 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2.25
11112 | Doe | Jean | 8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2
11111 | Smith | Bob | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2.5
【问题讨论】:
-
例如
stream >> student.quiz2;不会处理逗号。
标签: c++ csv struct delimiter ifstream