iostream problem


Hello,
I have a (understanding?) problem with the behaviour of the std::iostream class.
Specifically with the insertion operator. I have the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
  stringbuf sb;
  iostream ios(&sb);
  string s;

  ios << "   \t hello ";
  cout << sb.str() << endl;
  ios >> skipws >> s; // input mit skipws
  cout << "|" << s << "|" << endl;  // => |hello|
  ios << " world";
  cout << sb.str() << endl;
  string s2;
  ios >> skipws >> s2; // input
  cout << "|" << s2 << "|" << endl;  // => |  \t world| 


This code works fine printing |hello| and |world|
Bit if I just remove the trailing last space character of the string in the following line:

ios << " \t hello";
The second ios << " world"; does not work no more.
The stringbuf sb is unchanged and the output of the last cout is just:
||


Does anybody has an explanation for this behaviour?

I have changed my code, making both insertions to the stream first and than reading it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  stringbuf sb;
  iostream ios(&sb);
  string s;

  ios << "   \t hello";
  cout << sb.str() << endl;
  ios << " world";
  cout << sb.str() << endl;
  ios >> skipws >> s; // input mit skipws
  cout << "|" << s << "|" << endl;  // => |hello|
  //ios << " world";
  //cout << sb.str() << endl;
  string s2;
  ios >> skipws >> s2; // input
  cout << "|" << s2 << "|" << endl; => |world|

It does work this way.
But I do not understand the first behaviour anyway.
I found the solution by myself.
The problem is I wrote to the stream using the operator <<.
After reading using the operator<< the EOF Bit is set and nothing works no more for the stream.
Making a clear in between and it works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  stringbuf sb;
  iostream ios(&sb);
  string s;

  ios << "   \t hello";
  cout << sb.str() << endl;
  ios >> skipws >> s; // input mit skipws
  cout << "|" << s << "|" << endl;  // => |hello|
  ios.clear();
  ios << " world";
  cout << sb.str() << endl;
  string s2;
  ios >> skipws >> s2; // input
  cout << "|" << s2 << "|" << endl; 
Topic archived. No new replies allowed.