【发布时间】:2016-03-25 03:43:05
【问题描述】:
我正在尝试将我的一个旧程序从 C 移植到 C++。我无法想出代码来完成解析文件每一行的任务(由分号分隔)。我知道要将每一行读入一个字符串,我应该使用 std::getline() 并且还阅读了涉及 stringstream 的解决方案。但是,就将行解析为单个变量而言,我迷失了方向。以前,在 C 语言中,我使用的是 sscanf()。这是我的旧代码...
void loadListFromFile(const char *fileName, StudentRecordPtr *studentList) {
FILE *fp; // Input file pointer
StudentRecord student; // Current student record being processed
char data[255]; // Data buffer for reading line of text file
// IF file can be opened for reading
if ((fp = fopen(fileName, "r")) != NULL) {
// read line of data from file into buffer 'data'
while (fgets(data, sizeof(data), fp) != NULL) {
// scan data buffer for valid student record
// IF valid student record found in buffer
if (sscanf(data, "%30[^,], %d, %d, %d, %d, %d, %d, %d", student.fullName, &student.scoreQuiz1,
&student.scoreQuiz2, &student.scoreQuiz3, &student.scoreQuiz4, &student.scoreMidOne,
&student.scoreMidTwo, &student.scoreFinal) == 8) {
// Process the current student record into the student record list
processStudentToList(student, studentList);
}
}
}
else {
// Display error
puts("**********************************************************************");
puts("Could not open student record file.");
puts("**********************************************************************");
}
// Close file
fclose(fp);
}
还有我当前的代码,因为我被困在这个问题上,所以它是不完整的。
void Database::loadFromFile(const string filename) {
ifstream file(filename);
string data;
if ( file.is_open() ) {
cout << "Sucessfully loaded " << filename << ".\n" << endl;
while (getline(file, data)) {
//
}
}
else {
cerr << "Error opening input file.\n" << endl;
}
}
我将非常感谢任何与此方法等效的 C++ 的见解。
编辑:被标记为重复的帖子没有回答我的问题。该解决方案不考虑分号(或任何字符)分隔的字符串。
【问题讨论】:
标签: c++ io formatting