gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:56 24 4
gpt4 key购买 nike

我正在尝试找出处理文本输入的最佳方式,就像我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com