[英]c++ getline and stringstream
I'm trying to read in a file, which has 5 lines, and every line is 3-4 string long. 我正在尝试读取一个有5行的文件,每行的长度为3-4个字符串。 Here's my input file: 这是我的输入文件:
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
And this is what I get: 这就是我得到的:
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
This is my code: 这是我的代码:
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;
}
How can I read in the file without having the 3rd and 5th line filled with the 2nd and 4th line's time? 如何在没有第3行和第5行填充第2行和第4行的情况下读取文件? I want the dx.out to be empty. 我希望dx.out为空。 Should I use another method, or is it possible to be done with stringstream? 我应该使用其他方法,还是可以使用stringstream?
If >>
sees that there is nothing left in the stringstream
, it will leave the variable untouched - so dx.out
keeps its value from the last line. 如果>>
看到stringstream
没有任何内容,它将保持变量不变 - 所以dx.out
保持其最后一行的值。 However, you can do 但是,你可以这样做
ss >> dx.in >> dx.name >> dx.id;
if (!(ss >> dx.out))
dx.out = "";
because ss >> dx.out
returns ss
, and when a stream is converted to a bool
(such as when it is used in an if
condition), it returns false
if the last read attempt failed. 因为ss >> dx.out
返回ss
,并且当流转换为bool
(例如当它在if
条件中使用时),如果上次读取尝试失败,则返回false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.