C++ - repeatedly using istringstream
Asked Answered
R

2

22

I have a code for reading files with float numbers on line stored like this: "3.34|2.3409|1.0001|...|1.1|". I would like to read them using istringstream, but it doesn't work as I would expect:

  string row;
  string strNum;

  istringstream separate;  // textovy stream pro konverzi

   while ( getline(file,row) ) {
      separate.str(row);  // = HERE is PROBLEM =
      while( getline(separate, strNum, '|') )  { // using delimiter
        flNum = strToFl(strNum);    // my conversion
        insertIntoMatrix(i,j,flNum);  // some function
        j++;
      }
      i++;
    }

In marked point, row is copied into separate stream only first time. In next iteration it doesn't work and it does nothing. I expected it is possible to be used more times without constructing new istringstream object in every iteration.

Ripping answered 4/5, 2010 at 17:0 Comment(0)
Y
33

After setting the row into the istringstream...

separate.str(row);

... reset it by calling

separate.clear();

This clears any iostate flags that are set in the previous iteration or by setting the string. http://www.cplusplus.com/reference/iostream/ios/clear/

Yasukoyataghan answered 4/5, 2010 at 17:2 Comment(2)
Thanks a lot. That is very important information I was missing in many codes;)Ripping
Does it actually need to be after though? I think you can clear it before too.Selfdeceit
I
6

You need to add a separate.clear(); line after separate.str(row) to clear the status bits, otherwise the eofbit gets set and subsequent reads fail.

Inae answered 4/5, 2010 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.