stringstream good() return value with char vs. string

100 Views Asked by At

I would like to understand why ss.good() behavior is different when z below is a std::string vs. char, in particular why good() returns true in one case and false with other.

#include <iostream>
#include <sstream>

int main() {
   std::string line;
   while (getline(std::cin, line)) {
      std::cout << "Reading new line Size " << line.size() << "\n";
      std::stringstream ss{line};
      std::string z; // switch later to char
      ss >> z;
      if (ss.good()) {
         std::cout << "Stream good\n";
      } else {
         std::cout << "Not good\n";
      }
   }

}

With std::string z, the program output is

$ ./a.out
A
Reading new line Size 1
Not good

With char z, the program output is

$ ./a.out
A
Reading new line Size 1
Stream good
1

There are 1 best solutions below

1
BoP On BEST ANSWER

If you check the other status functions, I'm sure the difference is in ss.eof().

Reading a char only ever tries to read one character, and doesn't notice if there is anything more in the stream.