我想将我的一个旧程序从C移植到C++。我无法提供代码来完成解析文件的每一行(用分号分隔)的任务。我知道要将每行读入一个字符串,我应该使用std :: getline()并且还读取涉及stringstream的解决方案。但是,就解析行为单个变量而言,我已经失去了。以前,在C中,我使用了sscanf()。这是我的旧代码...如何在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++的任何洞察力等同于这种方法。
编辑:这被标记为重复的帖子不回答我的问题。该解决方案不考虑分号(或任何字符)分隔的字符串。
我已阅读此解决方案,但不确定如何使用此字符串由分号和非空格分隔。 – Cam
哦,我现在看到了问题。好吧,让我试试几件事:) – ddeunagomez
@Cam也许这就是你要找的东西? http://stackoverflow.com/questions/11719538/how-to-use-stringstream-to-separate-comma-separated-strings – yano