Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

stringstream good() return value with char vs. string

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading