问题描述
测试文件
11111,Smith,Bob,10,9,8,92,89,90
11112,Doe,Jean,7,84,88,89
11113,Hardy,Joe,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,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
解决方法
您的问题是,与抛出分隔符的 getline
不同,stream >> student.quiz1;
没有,因此当您尝试执行 {{1} }.您需要从流中取出那个逗号。您可以通过使用 ,
来“吃掉”角色,或使用命名的 stream >> student.quiz2;
像
get