在c++中处理fscanf等价的更好方法
Better way of handling of fscanf equivalent in c++
我正在努力找出处理文本输入的最佳方式,就像在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++中读取格式化数据?
相关文章:
- 初始化具有非默认构造函数的std::数组项的更好方法
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 编写按初始值循环的循环的更好方法是什么
- 用 c++ 为游戏制作"bullet"的更好方法?
- 在CMakeLists中包含目录的更好方法.txt
- 将QDomDocument数据用作文本的更好方法
- C++ - 创建具有相同字符的特定大小的以 null 结尾的 c 样式字符串的更好方法
- 在 sqlite3 中批量插入的更好方法C++
- 设计许多单例代码结构的更好方法
- 使用继承的类模板避免公共成员不可见和源代码膨胀/重复的更好方法
- 在初始化列表中初始化数组的更好方法
- 将对象从一个 std::d eque 移动到另一个的更好方法
- 请告诉我在巴泽尔拥有多平台工作空间的更好方法
- 构造具有大量数据的对象的更好方法(C++)
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 在C++中创建不可变对象的更好方法
- 在构造函数中组织初始值设定项列表的更好方法
- std::copy with return values - 防止"expression: string iterators incompatible"的更好方法?
- 删除数组成员的更好方法是什么?
- 在C 中操作数据的更好方法是什么