back to back input and output to stringstream

Below code is not working as expected.
stringstream ss;
int n;
ss<<"12";
ss>>n;
cout<<n<<endl;
ss<<"45";
ss>>n;
cout<<n<<endl;

Output:
12
12

Expected:
12
45
The operations affect the status of the stringstream. After the first input ss>>n; the eof flag is set. Subsequent operations on the same stream will fail.

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
29
30
31
32
#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    stringstream ss;
    int n;
    ss << "12";
    ss >> n;
    cout << n << endl;
    
    cout << boolalpha;
    
    cout << "good: " << ss.good() << '\n'
         << "bad:  " << ss.bad()  << '\n'
         << "fail: " << ss.fail() << '\n'
         << "eof:  " << ss.eof()  << '\n';
         
    ss << "45";

    cout << "\n\nAfter inserting \"45\" \n\n";
    
    cout << "good: " << ss.good() << '\n'
         << "bad:  " << ss.bad()  << '\n'
         << "fail: " << ss.fail() << '\n'
         << "eof:  " << ss.eof()  << '\n';
    
    ss >> n;
    cout << n << endl;           
} 
12
good: false
bad:  false
fail: false
eof:  true


After inserting "45"

good: false
bad:  false
fail: true
eof:  true
12


At the very least you would need to use clear() to reset the status flags. Possibly also empty the stream by allocating an empty string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    stringstream ss;
    int n;
    
    ss << "12";
    ss >> n;
    cout << n << endl;
             
    ss.clear();    // reset the status flags
    ss.str("");    // set empty string
    
    ss << "45";
    ss >> n;
    cout << n << endl;   
}

Last edited on
Two other alternatives:
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
29
30
31
32
#include <iostream>
#include <sstream>

int main()
{
    {
        std::stringstream stm ;

        stm << "12 " ; // note: space after the last character
        int n ;
        stm >> n ; // the stream is not at eof after this
        std::cout << n << '\n' ; // 12

        stm << "45" ;
        stm >> n ;
        std::cout << n << '\n' ; // 45
    }

    {
        // initialise with a stringbuf of size 4 characters
        std::stringstream stm( std::string( 4, ' ' ) ) ;

        stm << "12" ; // note: no space after the last character
        int n ;
        stm >> n ; // the stream is not at eof after this
        std::cout << n << '\n' ; // 12

        stm << "45" ;
        stm >> n ;
        std::cout << n << '\n' ; // 45
    }
}
Thanks Chervil (6904)
Topic archived. No new replies allowed.