在c ++中将制表符分隔的文件读入数组 [英] Read tabs separated file into arrays in c++

查看:36
本文介绍了在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 ++中将制表符分隔的文件读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆