C ++逐行读取文件,然后使用分隔符拆分每行 [英] C++ Read file line by line then split each line using the delimiter

查看:936
本文介绍了C ++逐行读取文件,然后使用分隔符拆分每行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要逐行读取txt文件,在读取每行后,我想根据选项卡\t拆分该行并将每个零件添加到结构中的元素。



my struct is 1 * char和2 * int

  struct myStruct 
{
char chr;
int v1;
int v2;
}

其中chr可以包含多个字符。



一行应该是:

  randomstring TAB编号TAB编号NL 


解决方案

尝试:

注意:如果chr可以包含更多

  std :: ifstream file(plop); 
std :: string line;

while(std :: getline(file,line))
{
std :: stringstream linestream(line)
std :: string data;
int val1;
int val2;

//如果您有真正的制表符分隔数据,请使用带有第三个参数的getline()。
//如果你的数据只是空格分隔的数据
//那么运算符>>将它做的(它读一个空格分隔的字成一个字符串)。
std :: getline(linestream,data,'\t'); //读取第一个选项卡(废弃选项卡)。

//使用运算符读取整数>>
linestream>> val1>> val2;
}


I want to read a txt file line by line and after reading each line, I want to split the line according to the tab "\t" and add each part to an element in a struct.

my struct is 1*char and 2*int

struct myStruct
{
    char chr;
    int v1;
    int v2;
}

where chr can contain more than one character.

A line should be something like:

randomstring TAB number TAB number NL

解决方案

Try:
Note: if chr can contain more than 1 character then use a string to represent it.

std::ifstream file("plop");
std::string   line;

while(std::getline(file, line))
{
    std::stringstream   linestream(line);
    std::string         data;
    int                 val1;
    int                 val2;

    // If you have truly tab delimited data use getline() with third parameter.
    // If your data is just white space separated data
    // then the operator >> will do (it reads a space separated word into a string).
    std::getline(linestream, data, '\t');  // read up-to the first tab (discard tab).

    // Read the integers using the operator >>
    linestream >> val1 >> val2;
}

这篇关于C ++逐行读取文件,然后使用分隔符拆分每行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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