【发布时间】:2009-04-05 19:45:25
【问题描述】:
我在尝试用 C++ 读取文件时遇到了很多麻烦。 我遇到的主要问题是正确读取流的第一行,因为它与所有其他行不同。
一个示例文件是:
#Newbie 101|Exam 1|3
Person One|10
Person Two|20
Person Three|30
第一行以 # 开头并声明班级名称、分配名称和学生总数。
void Grading::loadData()
{
string filename;
cout << "Enter a filename with records to open: ";
cin >> filename;
std::ifstream file;
file.open(filename.c_str(), std::ios::app);
if (!file) {
cout << "Unable to open the specified file" << endl;
return;
}
string buffer;
vector<Student> students;
vector<Student>::iterator it;
while (!getline(file, buffer, '|').eof()) {
Student stud;
string name;
string tmpgrade;
string course;
string assignment;
int totalstudents;
// read first line
if (buffer.find("#") == 0) {
getline(file, course, '|');
cout << "Course Name : " << course << endl;
cout << "Grading Item : " << assignment << endl;
cout << "Total Students : " << totalstudents << endl;
cout << endl;
continue;
}
getline(file, name, '|');
getline(file, tmpgrade, '|');
double grade = strtod(tmpgrade.c_str(), NULL);
stud.name = name;
stud.grade = grade;
cout << "Name: " << stud.name << endl;
cout << "Grade: " << stud.grade << endl;
students.push_back(stud);
}
我非常感谢有关如何修复此代码以正确读取文件的任何建议。 提前非常感谢!
【问题讨论】:
-
我建议您自己寻找作业的答案。这样你就可以确保你真正学到了一些东西,如果有人发现你在这里得到了答案,你就不会受到惩罚;-)