Suppose my code is:
int x = 4;
string alpha;
Now i want to print x using alpha, that is using
cout << alpha;
For example in this case i want 4 to be printed on screen, how to do this ?
Suppose my code is:
int x = 4;
string alpha;
Now i want to print x using alpha, that is using
cout << alpha;
For example in this case i want 4 to be printed on screen, how to do this ?
If you have C++11, you can use std::to_string(x)
.
Pre C++11 it was a little more difficult. You could use std::stringstream
:
std::stringstream ss;
ss << 4;
std::string alpha = ss.str();
int x = 4;
string alpha = to_string(x);
cout << alpha;
To answer the question in your comment: you can turn multiple numbers into one string by concatenating their string values:
alpha = to_string(x1) + to_string(x2)
Or with a space in between:
alpha = to_string(x1) + " " + to_string(x2)
A good way is to create your own function so then you can reuse it everywhere.
std::string toString (int a)
{
std::stringstream mynewstream;
mynewstream << a;
return mynewstream.str();
}
Then if you want to do concatenate some it's easy:
cout << "This subject has been posted already" << toString(4000) << " times.";
or
int a = 1;
int b = 2;
string concat = toString(a) + toString(b);
cout << concat;
Will output: "12"