How to “sscanf” in C++?
我正试图把一个旧的程序从C移植到C++。我很难想出代码来完成解析文件每一行(用分号分隔)的任务。我明白,要把每一行读到字符串中,我应该使用STD::GETLIN(),并且还阅读涉及String String的解决方案。但是,在将行解析为单个变量时,我会迷失方向。以前,在C语言中,我使用了sscanf()。这是我的旧密码…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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); } |
以及我当前的代码,由于我在这个问题上被卡住了,它是不完整的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | void Database::loadFromFile(const string filename) { ifstream file(filename); string data; if ( file.is_open() ) { cout <<"Sucessfully loaded" << filename <<". " << endl; while (getline(file, data)) { // } } else { cerr <<"Error opening input file. " << endl; } } |
我非常感谢C++对这种方法的任何洞察力。
编辑:这个被标记为重复的帖子没有回答我的问题。该解决方案不考虑分号(或任何字符)分隔的字符串。
我相信这就是你所追求的:我应该用什么来代替SScanf?
1 2 3 4 5 6 7 8 9 10 | #include <sstream> std::ifstream file( fileName ); if ( file ) { //Check open correctly std::stringstream ss; ss << file.getline(); int a, b, c; ss >> a >> b >> c; } |
您可以使用
例子:内容为"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> #include <fstream> #include <string> #include <vector> int main() { std::ifstream in_file("file", std::ios::in); if (!in_file.is_open()) { std::cerr <<"File not open" << ' '; return -1; } std::vector<std::string> vec; std::string word; while (std::getline(in_file, word, ',')) { vec.emplace_back(word); } for (const auto& i : vec) std::cout << i << ' '; } |
意志产出:
1 2 3 | name id age |
您可以使用它将其存储到变量中。