C ++读取多个列的文件 [英] C++ Read File with multiple column

查看:128
本文介绍了C ++读取多个列的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一个包含多个列,不同变量类型的文件。列数不确定,但在2或4之间。例如,我有一个文件:

I'd like to read a file with multiple columns, different variable types. The number of columns is uncertain, but between 2 or four. So for instance, I have a file with :



  • string int

  • string int string double

  • string int string

  • string int string double

  • string int
  • string int string double
  • string int string
  • string int string double

谢谢!

我编辑,将列数更正为2或5,而不是4五是原来写的。

I edited to correct the number of columns to between 2 or 5, not 4 or five as originally written.

推荐答案

您可以先阅读 std :: getline

You can first read the line with std::getline

std::ifstream f("file.txt");
std::string line;
while (std::getline(f, line)) {
...
}

,然后使用 stringstream

and then parse this line with a stringstream

std::string col1, col3;
int col2;
double col4;
std::istringstream ss(line);
ss >> col1 >> col2;
if (ss >> col3) {
    // process column 3
    if (ss >> col4) {
        // process column 4
    }
}

如果列可能包含不同类型,则必须首先读入字符串然后尝试确定正确的类型。

If the columns might contain different types, you must first read into a string and then try to determine the proper type.

这篇关于C ++读取多个列的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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