我正在尝试读取一个有5行的文件,每行的长度为3-4个字符串。 这是我的输入文件:
10:30 Hurley 1234567A 10:15
10:45 Hurley 1234567A 11:30
08:35 Jacob 1x1x1x1x1x
08:35 Jacob 1x1x1x1x1x 08:10
08:05 Jacob 1x1x1x1x1x
08:45 Sayid 33332222 09:15
这就是我得到的:
10:30 Hurley 1234567A 10:15
10:45 Hurley 1234567A 11:30
08:35 Jacob 1x1x1x1x1x 11:30
08:35 Jacob 1x1x1x1x1x 08:10
08:05 Jacob 1x1x1x1x1x 08:10
08:45 Sayid 33332222 09:15
这是我的代码:
void enor::Read(status &sx,isle &dx,ifstream &x){
string str;
getline(x, str, '\n');
stringstream ss;
ss << str;
ss >> dx.in >> dx.name >> dx.id >> dx.out;
/*getline(x, str, '\n');
x>>dx.in>>dx.name>>dx.id>>dx.out;*/
if(x.fail())
sx=abnorm;
else
sx=norm;
}
如果没有第3行和第5行填充第2行和第4行的时间,我怎么能读入文件?我希望dx.out为空。我应该使用其他方法,还是可以使用stringstream?
答案 0 :(得分:3)
如果>>
发现stringstream
中没有任何内容,则会保持变量不变 - 因此dx.out
会保留其最后一行的值。但是,你可以做到
ss >> dx.in >> dx.name >> dx.id;
if (!(ss >> dx.out))
dx.out = "";
因为ss >> dx.out
返回ss
,当流转换为bool
时(例如在if
条件下使用时),它会返回{{ 1}}如果上次读取尝试失败。