c++ - 在 C++ 中处理 fscanf 等效项的更好方法

标签 c++ file input

我试图找出处理文本输入的最佳方法,就像我在 C 中使用 fscnaf 一样。

下面的内容似乎适用于包含...的文本文件

string 1 2 3
string2 3 5 6

我也想要。它读取每行上的各个元素并将它们放入各自的 vector 中。您认为这是处理输入的好方法吗?输入始终以字符串开头,然后每行包含相同数量的数字。

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

最佳答案

对于您的代码,请阅读以下内容:Why is iostream::eof inside a loop condition considered wrong?


既然您知道格式,请使用 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 file\n";
        }
        return 0;
}

输出:

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

我受到了这个启发:How to read formatted data in C++?

关于c++ - 在 C++ 中处理 fscanf 等效项的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36374655/

相关文章:

c++ - 使用类对象提升线程 worker

javascript - 将 Blob 对象转换为文件,对于 Ms Edge

IE8 的 Javascript 占位符不起作用

Java HTML 输入表单名称

c++ - 静态和共享库链接器错误

c++ - 与或运算符

c++ - 是否可以在原始字符串文字中插入转义序列?

javascript - Ionic 2 - (任何窗口).resolveLocalFileSystemURL() 抛出错误

node.js - 如何使用 Restify 提供静态文件

html - 将图标放在表单中的输入元素中(不是作为背景图像!)