使用fstream读取所选列

时间:2016-02-25 22:20:56

标签: c++ file input fstream

我使用以下代码从文件中读取我的数据,但我的问题是我只想从文件中的更多列中捕获一些列。有没有比我正在使用的方法更好的方法。

if (file_exists($file)) {require $file;}

1 个答案:

答案 0 :(得分:0)

如果列与空格对齐,每个列从一个位置开始,是列号和常量的倍数,则可以使用std::istream::ignorestd::istream::seekg函数跳过某些行。

如果不是这样,至少可以通过使用此功能使代码更漂亮:

std::istream &skip_row(std::istream &is, unsigned int count)
{
    std::string s;

    while(count-- && is >> s) {}

    return is;
}

您可以将其设为接受各种类型的模板,或者您可以为类重载operator>>以获得与此不同的语法:

data_out >> age_p && skip_row(data_out, 5) && data_out >> bcs_p >> ...

一种天真的方法是将所有行读入std::vector<std::string>然后将其编入索引,但由于内存分配过多会对性能产生影响。