-1

How do I assign an int to a string with stringstream?

The "stringstream(mystr2) << b;" doesn't assign b to mystr2 in the example below:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string mystr = "1204";
    int a;
    stringstream(mystr) >> a;
    cout << a << endl; // prints 1204

    int b = 10;
    string mystr2;
    stringstream(mystr2) << b;
    cout << mystr2 << endl; // prints nothing
    return 0;
}
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
Ricardo Zorio
  • 282
  • 5
  • 11

5 Answers5

4

This should do:

stringstream ss;
ss << a;
ss >> mystr;

ss.clear();
ss << b;
ss >> mystr2;
billz
  • 44,644
  • 9
  • 83
  • 100
  • 1
    Hmm, he had the trouble with the second part, not the first, no? :) 'b' would have been clearer in there with mystr2. – László Papp Aug 30 '13 at 22:38
1
int b = 10;
string mystr2;
stringstream ss;
ss << b;
cout << ss.str() << endl; // prints 10
CS Pei
  • 10,869
  • 1
  • 27
  • 46
1

When you create a string stream with the ctor stringstream(mystr2) the mystr2 is copied as the initial content of the buffer. mystr2 is not modified by subsequent operations on the stream.

To get the content of the stream you can use the str method:

int b = 10;
string mystr2;
stringstream ss = stringstream(mystr2);  
ss << b;
cout << mystr2.str() << endl; 

See constructor and str method.

0

This will print out the '10' correctly below.

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string mystr = "1204";
    int a;
    stringstream(mystr) >> a;
    cout << a << endl; // prints 1204

    int b = 10;
    string mystr2;
    stringstream ss;
    ss << b;
    ss >> mystr2;
    cout << mystr2 << endl; // prints 10
    return 0;
}
László Papp
  • 51,870
  • 39
  • 111
  • 135
0

The answer to your literal question is:

int b = 10;
std::string mystr2 = static_cast<stringstream &>(stringstream()<<b).str();
cout << mystr2 << endl;
jxh
  • 69,070
  • 8
  • 110
  • 193