Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jul 2008
    Thanked 0 Times in 0 Posts

    c++ stringstream

    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

  • #2
    Regular Coder ralph l mayo's Avatar
    Join Date
    Nov 2005
    Thanked 31 Times in 29 Posts
    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:

        std::stringstream ss;
        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.

        int rv;
        ss >> rv;
        return rv;
    So concat(2, 2) == 22. Admittedly that example isn't very useful but more practical applications come up all the time.


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts