2013-05-04 98 views
4

我试图阅读一个文件,它有5行,每行是3-4字符串长。 这是我的输入文件:C++ getline和stringstream

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; 
} 

我怎样才能在文件中,而无需第三读第五行填满第二行和第四行的时间?我希望dx.out是空的。我应该使用另一种方法,还是可以用stringstream来完成?

+0

你能告诉你如何调用这个函数吗?你是否在重复使用'dx'对象? – 2013-05-04 12:19:09

+0

void enor :: First(){ Read(sx,dx,x); Next(); } void enor :: Next(){ end = sx == abnorm; if(!end)current.in = dx.in; current.name = dx.name; current.id = dx.id; current.out = dx.out; 阅读(sx,dx,x); (xx.in> current.out) Read(sx,dx,x); } */ } } – wfmn17 2013-05-04 12:25:58

回答

3

如果>>看到stringstream中没有任何内容,它将保留该变量不变 - 所以dx.out保留其最后一行的值。但是,你可以做

ss >> dx.in >> dx.name >> dx.id; 
if (!(ss >> dx.out)) 
    dx.out = ""; 

因为ss >> dx.out回报ss,当流转换为bool(当它在if条件中使用如),它返回false,如果最后一次读尝试失败。

+0

谢谢,作品完美! – wfmn17 2013-05-04 12:33:01