C ++ getline and stringstream

I am trying to read in a file that has 5 lines and each line is 3-4 lines long. Here is 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 here 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 a file without having 3rd and 5th lines filled with second and fourth lines? I want dx.out to be empty. Should I use a different method, or can this be done using stringstream?

+4
source share
1 answer

If >> sees that there is nothing left in stringstream , it will leave the variable untouched - therefore dx.out saves its value from the last line. 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 the stream is converted to bool (for example, when it is used in the if state), it returns false if the last read attempt failed.

+3
source

Source: https://habr.com/ru/post/1479129/


All Articles