You are here

How to reuse an istringstream?

Obviously, you use the method istringstream::str(std::string&). But you must consider the status flags.

Example:
  std::string sstr1("1.0 2");
  std::string sstr2("1.0 2");
  int i;
  double d;

  std::istringstream ist(sstr1);
  ist >> d;
  // actual state : d = 1.0; sstr1 = " 2"

  ist.str(sstr2);
  // okay, actual state: ist = "1.0 2"

  ist >> d >> i;
  // actual state: d = 1.0, i = 2, ist =""

  ist.str(sstr1);
  // an error occured, the actual state is: ist = ""

The last initialization failed. The reason is that the stream remembers its state and saves it in various status bits. The state can be checked with the methods good(), eof (), fail () and bad (). A stream, whose state is not good(), ignores any further action. This happened in the above case, since the stream after the extraction of its last character is empty and the state is now not good() anymore, but eof(). In order to set the stream back into the good() state, the method clear() must be called. This extends the example above to:

  std::string sstr1("1.0 2");
  std::string sstr2("1.0 2");
  int i;
  double d;

  std::istringstream ist(sstr1);
  ist >> d;
  // actual state : d = 1.0; sstr1 = " 2"

  // if the state is not good(), call clear()
  if (!ist.good())
    ist.clear();
  ist.str(sstr2);
  // okay, actual state: ist = "1.0 2"

  ist >> d >> i;
  // actual state: d = 1.0, i = 2, ist =""

  // you can call clear() anyway
  ist.clear();
  ist.str(sstr1);
  // actual state : ist = "1.0 2"