我使用以下代码从文件中读取数据,但我的问题是我只想从文件中的更多列中捕获一些列。有没有比我使用的方法更好的方法。
void Data::read_simulated (const string &filepath)
{
ifstream data_out (filepath.c_str());
if (!data_out)
cout<<"Failed to open"<<endl;
else
{
string id_p,age_p, dim_p, my_p, mcf_p, mcp_p, mcl_p, bw_p, bcs_p;
string dummy_line, g;
getline(data_out, dummy_line);
while(data_out>>age_p>>g>>g>>g>>g>>g>>g>>g>>bcs_p>>g>>g>>my_p>>g>>g>>bw_p>>g>>g>>dim_p>>g>>g>>g>>g>>g>>g>>g>>g>>g>>g>>g>>g>>g)
{
//s.cow_id.push_back(get_number(id_p));
if (get_number(age_p)>=1424.0 &&get_number(age_p)<=1733.0)
{
age_pre.push_back(age_p);
dim_pre.push_back(dim_p);
my_pre.push_back(my_p);
//mcf_obs.push_back(get_number(mcf_p));
// mcp_obs.push_back(get_number(mcp_p));
//mcl_obs.push_back(get_number(mcl_p));
bw_pre.push_back(bw_p);
bcs_pre.push_back(bcs_p);
}
}
data_out.close();
}
}
如果列与空格对齐,每个列从行中的位置开始,是列号和常量的倍数,则可以使用 std::istream::ignore
或 std::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>
,然后为其编制索引,但由于内存分配过多,这将对性能产生影响。