Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Easiest way to convert int to string in C++

What is the easiest way to convert from int to equivalent string in C++?
I am aware of possible methods. Is there any easier way to implement it?
(1)

int a = 10;
char *intStr = itoa(a);
string str = string(intStr);

(2)

int a = 10;
stringstream ss;
ss << a;
string str = ss.str();
by

2 Answers

Bharatgxwzm
I normally apply the following process:
#include <sstream>

template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
MounikaDasa
We also had to_string() built-in method in c++ that accepts a value of any basic data type and converts it into a string.

Below is an example:

#include <iostream>
#include<string>
using namespace std;

int main() {
int num = 100; // a variable of int data type

string str; // a variable of str data type
str = to_string(num); // using to_string to convert an int into a string
cout << "The integer value is " << num << endl;
cout << "The string representation of the integer is " << str << endl;
}

Login / Signup to Answer the Question.