0

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 ?

Nishu
  • 191
  • 1
  • 1
  • 11

3 Answers3

3

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();
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1
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)
Lee White
  • 3,649
  • 8
  • 37
  • 62
1

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"

blackmesa
  • 250
  • 4
  • 14