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];
    }
  }


}

Recommended Answers

All 4 Replies

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).

what does the input to your program look like?

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.