在c++中处理fscanf等价的更好方法

Better way of handling of fscanf equivalent in c++

本文关键字:更好 方法 fscanf c++ 处理      更新时间:2023-10-16

我正在努力找出处理文本输入的最佳方式,就像在C.中使用fscnaf一样

以下内容似乎适用于包含…的文本文件。。。

string 1 2 3
string2 3 5 6

我也想要。它读取每行上的各个元素,并将它们放入各自的向量中。你认为这是处理输入的好方法吗?输入总是以一个字符串开头,然后每行都跟着相同数量的数字。

int main(int argc, char* argv[])
{
ifstream inputFile(argv[1]);
vector<string> testStrings;
vector<int> intTest;
vector<int> intTest2;
vector<int> intTest3;
string testme;
int test1;
int test2;
int test3;
if (inputFile.is_open())
{
    while (!inputFile.eof())
    {
        inputFile >> testme;
        inputFile >> test1;
        inputFile >> test2;
        inputFile >> test3;
        testStrings.push_back(testme);
        intTest.push_back(test1);
        intTest2.push_back(test2);
        intTest3.push_back(test3);
    }
    inputFile.close();
}
else
{
    cout << "Failed to open file";
    exit(EXIT_FAILURE);
}
return 0;
}

更新

我已将while循环更改为。。。有更好的吗?

    while (getline(inputFile, line))
    {
        istringstream iss(line);
        iss >> testme;
        iss >> test1;
        iss >> test2;
        iss >> test3;
        testStrings.push_back(testme);
        intTest.push_back(test1);
        intTest2.push_back(test2);
        intTest3.push_back(test3);
    }

对于您的代码,请阅读:为什么循环条件中的iostream::eof被认为是错误的?


既然您知道格式,使用ifstream,您就可以轻松地编写更少的代码来实现相同的(或更好的结果):

#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char* argv[]) {
        std::ifstream ifs;
        if(argc > 1) {
                ifs.open(argv[1]);
        } else {
                std::cout << "Usage: " << argv[0] << " <filename>n";
                return -1;
        }
        std::string str;
        int v1 = -1, v2 = -1, v3 = -1
        if (ifs.is_open()) {
                while(ifs >> str >> v1 >> v2 >> v3)
                        std::cout << str << ' ' << v1 << ' ' << v2 << ' ' << v3 << std::endl;
        } else {
                std::cout << "Error opening filen";
        }
        return 0;
}

输出:

gsamaras@gsamaras:~$ g++ -Wall readFile.cpp 
gsamaras@gsamaras:~$ ./a.out test.txt 
string 1 2 3
string2 3 5 6

我受到了启发:如何在C++中读取格式化数据?