Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stringstream returning extra character?

I've been attempting to use the C++ stringstream class to do some relatively simple string manipulations, but I'm having a problem with the get() method. For some reason whenever I extract the output character by character it appends 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;
}

The output from the program is:

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

Any help you can give me on this would be appreciated.

like image 318
Chris Avatar asked May 23 '26 15:05

Chris


1 Answers

At the end of the stream ss.eof() doesn't know yet that the end of the stream will be reached soon, but the following extraction of a character fails. Since the extraction failed because the end of the stream was reached, c is not changed. Your program doesn't recognize that ss.get(c) failed and prints that old value of c again.

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

while (ss.get(c)) {
   cout << "char: " << c << endl;
}
like image 90
sth Avatar answered May 26 '26 03:05

sth