Hi all. I want to take a set number of characters from a stringstream at a time and display them to the console as per my code below. Because of when the first blank space is reached the process terminates due to teh eofbit flag. Is there any way around this in c++.

Thank you.

#include <iostream>
#include <string>
#include <sstream>
#include <istream>

using namespace std;

int main()
  char mychar[4];
  string mystring;
  stringstream mystream;

  cout << "enter a string" << endl;

  cin >> mystring;

  mystream << mystring;

//Now view the output

  while (mystream.get(mychar,4))
    for (int i = 0; i < 3; i++)
        cout << mychar[i];

4 Years
Discussion Span
Last Post by furalise

That's because your stringstream really does only contain the first word. Why? You used operator>> to populate mystring from cin, and operator>> stops reading at whitespace. Try using getline instead.


Yes, this is true and I've corrected that now. Though extracting a number of characters from a string at a time still poses the same problem. I have a work-around for this using the remainder function in c++ to determine the length of the string and then using the result to access the remaining characters (outside the initial loop). I just hoped there may be a simpler approach (ie.. turning off the eofbit flag which presents a new problem).

Edited by furalise


Like this..Let's say Im taking 6 characters at a time. There will be that error on the last character if I'm directly using get or read. This is due to that chunk containing white space at the end of the line.

(first line: 43 characters)
The rain fell mainly on the plain in spain
(second line 29 characters)
It is cold in the winter time

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.