about string streams?

closed account (Dy7SLyTq)
ive googled them, but i cant find a good explanation of them. what do they do that class istream doesnt?
If you've googled them, pretty much any link you click with example code will show them doing something that can't be done with an istream or ostream.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//Third party library header
class Money
{
    private:
        int cents;
    public:
        Money(int _cents) : cents(_cents) {};
    friend std::ostream & operator<< (std::ostream & , Money);
};

//Third party precompiled library 
std::ostream & operator<< (std::ostream & left, Money right)
{
    left << (right.cents/100) << '.' << (right.cents % 100);
    return left;
}

//Our 10 years old library
void legacy_function(char*);

//We need to make them to go along:
int main()
{
    Money pay(654);
    stringstream x;
    x << pay;
    legacy_function( x.str().c_str() );
}
Last edited on
> what do they do that class istream doesnt?

Nothing, except for a class-specific constructor and the member function str().

The heavy lifting is done by std::stringbuf.
std::istringstream is just ultra-thin facade over a std::istream that is composed with a std::stringbuf.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <sstream>

int main()
{
    std::stringbuf buf( "0 1 2 3 4 5 how now brown cow.", std::ios::in ) ;
    auto stdinbuf = std::cin.rdbuf( &buf ) ;

    int i ; while( std::cin >> i ) std::cout << i << ' ' ; // 0 1 2 3 4 5
    std::cout << '\n' ;

    std::cin.clear() ;
    std::string s ; std::getline( std::cin, s ) ;
    std::cout << s << '\n' ; // how now brown cow.

    std::cin.rdbuf(stdinbuf) ;
}

http://liveworkspace.org/code/2haWvs$0
Last edited on
Topic archived. No new replies allowed.