【问题标题】:How to "sscanf" in C++?如何在 C++ 中“sscanf”?
【发布时间】: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


    【解决方案1】:

    我相信这就是您所追求的: What should I use instead of sscanf?

    #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;
    }
    

    【讨论】:

    • 我已阅读此解决方案,但不确定当字符串由分号而不是空格分隔时如何使用此解决方案。
    • 哦,我现在看到了问题所在。好的,让我尝试几件事:)
    • @Cam 也许这就是您要找的东西? stackoverflow.com/questions/11719538/…
    • 另一种非常优雅的方式来处理逗号/分号或你有什么在this答案中显示;然后你可以编码while (file &gt;&gt; student.fullName &gt;&gt; ',' &gt;&gt; student.scoreQuiz1 &gt;&gt; ',' ...等...
    • 正是我想要的。谢谢!
    【解决方案2】:

    您可以使用std::getline 并使用分隔符,

    示例:
    内容为“name,id,age”的文件

    #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" << '\n';
          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 << '\n';
    }
    

    将输出:

    name
    id
    age
    

    您可以使用它来将其存储到变量中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      相关资源
      最近更新 更多