Woes of strstream

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
Examiner
New poster
Posts: 28
Joined: Thu Feb 19, 2004 1:19 pm

Woes of strstream

Post by Examiner »

I've been able to keep strstream objects local before. But not this time. Now I need a global strstream object (as my global functions need it), which has to be emptied before every test case.

I've tried to use a reference by declaring
[cpp]strstream ∈[/cpp]
However, whenever I say
[cpp]int main() {
strstream temp;
in = temp;
}[/cpp]
I get a complaint. It seems to me that strstream objects are not like ordinary ones; they are references themselves!

Also, like other STL objects, in.clear() is of no use.

Is there a feasible way?
UFP2161
A great helper
Posts: 277
Joined: Mon Jul 21, 2003 7:49 pm
Contact:

Post by UFP2161 »

Doesn't this work?

[cpp]
strstream *in;

int main()
{
while(cin >> blah)
{
in = new strstream(blah);
doit();
delete in;
}
}
[/cpp]
Examiner
New poster
Posts: 28
Joined: Thu Feb 19, 2004 1:19 pm

Post by Examiner »

Thank you very much for your suggestion. Your code works very well.

The only problem is that I then need lots of ugly
[cpp](*in) >> n;[/cpp]
instead of
[cpp]in >> n;[/cpp]

I am thinking of defining
[cpp]istream *operator>>(istream *in, int &n);
istream *operator>>(istream *in, char &c);
// etc.[/cpp]
though I do not know how to go about it generically.
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba »

It's better to use istringstreams and ostringstreams instead of strstreams. strstream is non standard and gcc supports it only for backward compatibility.

If your function needs the stream, why don't you pass it as an argument?
Examiner
New poster
Posts: 28
Joined: Thu Feb 19, 2004 1:19 pm

Post by Examiner »

The longer I think about it, the easier my question looks. You are right, Krzysztof, I could do that, at the cost of a bit more typing.

I could also create a big struct/class to include everything. For each test case, I declear an object of it and consequently get an empty strstream object.
[cpp]struct solver {
strstream in;

solver(string s) {
in << s;
}

//...
};

int main() {
string s;

while (getline(cin, s)) {
solver temp(s);
temp.solve();
}
}[/cpp]
Post Reply

Return to “C++”