Read tabs separated file into arrays in c++(在c ++中将制表符分隔的文件读入数组)
问题描述
我有这样的文件:
int1--tab--int2--tab--int3--tab--int4--tab--换行
int1--tab--int2--tab--int3--tab--int4--tab--newline
int1--tab--int2--tab--int3--tab--int4--tab--换行
int1--tab--int2--tab--int3--tab--int4--tab--newline
int1--tab--int2--tab--int3--tab--int4--tab--换行...
int1--tab--int2--tab--int3--tab--int4--tab--newline ...
我想将每一行保存到一个数组中.我的意思是所有 int1 都放入一个数组中,并想做同样的事情 int2 int3 ...
I want to save each row in to an array. I mean all int1 in to an array and want to do the same whit int2 int3 ...
我真的不知道该怎么做,请帮助我
I realy dont know how to do it please help me
我已经尝试逐行阅读了
#include <sstream>
#include <string>
std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
int a, b;
if (!(iss >> a >> b)) { break; }
}
推荐答案
您使用字符串流的想法是正确的.由于可能会再次使用读取分隔文件的代码,因此您可能会发现将其放入类中很有用.这是我个人的分隔 FileReader 类的摘录:
You had the right idea using a stringstream. Since code to read delimited files is likely to be used again, you may find it useful to put this into class. Here's an excerpt from my personal delimited FileReader class:
bool FileReader::getrow(RowMap &row){
std::string line = "";
if(std::getline(filehandle,line)){
std::stringstream line_ss(line);
std::string column = "";
unsigned int index = 0;
while(std::getline(line_ss,column,delimiter)){
if(index < headers.size()){
row[headers[index]] = column;
index++;
}
else{
break;
}
}
return true;
}
return false;
}
其中 RowMap 是以下的 typedef:
Where RowMap is a typedef of:
typedef std::unordered_map<std::string,std::string>
而 headers 是一个 typedef:
And headers is a typedef of:
typedef std::vector<std::string> RowHeadersVector;
并且应该有你的列名:
RowHeadersVector headers;
headers.push_back("column_1");
在我的示例中,我使用的是字符串到字符串的映射,但您可以轻松地将其更改为:
In my example, I'm using a map of string to string, but you could easily change it to:
typedef std::unordered_map<std::string,int>
使用这样的地图的好处是可以自行记录代码:
The benefit of using a map like this is self documented code:
row["column_1"]
这篇关于在c ++中将制表符分隔的文件读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在c ++中将制表符分隔的文件读入数组
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
