如何在C ++中使用“sscanf”?

时间:2016-03-25 03:43:05

标签: c++ io formatting

我正在尝试将我的旧程序从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 ++的见解。

编辑:这个标记为重复的帖子不回答我的问题。该解决方案不考虑分号(或任何字符)分隔的字符串。

2 个答案:

答案 0 :(得分:1)

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

inSampleSize

答案 1 :(得分:0)

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

示例:
包含内容&#34; name,id,age&#34;

的文件
#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

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