C ++ stringstream returns extra character?

I'm trying to use the C ++ stringstream class to do some pretty simple string manipulation, but I'm having a problem with the get () method. For some reason, when I extract the output character by character, it adds a second copy of the final letter.

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
   stringstream ss("hello");
   char c;

   while(!ss.eof()) {
      ss.get(c);
      cout << "char: " << c << endl;
   }
   return 0;
}

      

Exiting the program:

char: h
char: e
char: l
char: l
char: o
char: o

      

Any help you can give me would be appreciated.

+2


source to share


3 answers


At the end of the stream, ss.eof()

it is not yet known that the end of the stream will be reached anytime soon, but the next character extraction will fail. Since the retrieval failed because the end of the stream has been reached, c

does not change. Your program won't recognize what ss.get(c)

failed and will print that old value again c

.

The best way to check if there is still a character that can be read from the stream is to loop like this:



while (ss.get(c)) {
   cout << "char: " << c << endl;
}

      

+8


source


due to the order of the loop. Your reading \ 0 and EOF.

reorder your code like this



int main() {
   stringstream ss("hello");
   char c;

   ss.get(c);
   while(!ss.eof()) {
      cout << "char: " << c << endl;
      ss.get(c);
   }
   return 0;
}

      

+2


source


The EOF flag is only set if you are trying to read the PAST at the end of the file. The following code fixes the issue by testing for EOF after get () instead:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
   stringstream ss("hello");
   char c;

   while(1) {
      ss.get(c);
      if(ss.eof())
          break;

      cout << "char: " << c << endl;
   }
   return 0;
}

      

+1


source







All Articles