View Full Version : c++ stringstream
07-15-2008, 05:14 AM
What is the point of using this (in terms I'll understand)?
Can't we just use cin >> a instead to work out values?
Bear in mind I'm a newb
ralph l mayo
07-22-2008, 10:50 PM
If you already have data in a stream like cin then a stringstream isn't usually necessary.
It's helpful when you have data that comes from some other, non-stream source. stringstreams are both input AND output streams, so you can push your own data on them and pull it back out in the format you need, saving yourself the trouble of doing some tricky manual conversions.
Supposed you wanted to write a function that would concatenate two numbers (I don't know why, but it's a simple example).
int concat(const int a, const int b)
Obviously you can't just return a + b or anything so simple. You need a and b to be treated like their characters rather than their numeric value. Enter stringstream:
ss << a << b;
You're not allowed to stick your own data in cin like this, and if you stick it an output stream like cout you can't get it back.
Now ss contains the character data '22'... You could get it back directly with ss.str() but the function returns an int, so we need to use the formatting extractor to get the string reinterpreted as an integer again.
ss >> rv;
So concat(2, 2) == 22. Admittedly that example isn't very useful but more practical applications come up all the time.
Powered by vBulletin® Version 4.2.2 Copyright © 2017 vBulletin Solutions, Inc. All rights reserved.