时间:2019-05-11 标签:c++getline和stringstream
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16374187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ getline and stringstream
提问by wfmn17
I'm trying to read in a file, which has 5 lines, and every line is 3-4 string long. Here's my input file:
我正在尝试读取一个文件,该文件有 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
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? I want the dx.out to be empty. Should I use another method, or is it possible to be done with stringstream?
如何在没有第 3 行和第 5 行填充第 2 行和第 4 行时间的情况下读取文件?我希望 dx.out 为空。我应该使用另一种方法,还是可以使用 stringstream 来完成?
回答by Aasmund Eldhuset
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. However, you can do
如果>>
看到 中没有任何东西stringstream
,它将dx.out
保持变量不变 - 所以保持它的值从最后一行开始。但是,你可以这样做
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
return ss
,并且当流转换为 a 时bool
(例如在if
条件中使用时),false
如果上次读取尝试失败,则返回。