how do you convert an int to a string in c++?

?2007-02-25T07:05:44Z

Favorite Answer

conversion of an int to a string in c++, using a stringstream object :
method 1:

#include <iostream>
#include <sstream> // Required for stringstreams
#include <string>

std::string IntToString ( int number )
{
std::ostringstream oss;
// Works just like cout
oss<< number;

// Return the underlying string
return oss.str();
}

int main()
{
int number = 12345;
std::string result = IntToString ( number );

// Now we can use concatenation on the number!
std::cout<<"~~{" + result + "}~~\n";
}


method 2 : it will display as true r false

#include <sstream>
#include <string>

using namespace std;

bool StringToInt(const string &s, int &i);

int main(void)
{
string s1 = "12";
string s2 = "ZZZ";
int result;

if (StringToInt(s1, result))
{
cout << "The string value is " << s1
<< " and the int value is " << result << endl;
}
else
{
cout << "Number conversion failed" <<endl;
}
if (StringToInt(s2, result))
{
cout << "The string value is " << s2
<< " and the int value is " << result << endl;
}
else
{
cout << "Number conversion failed on " <<s2 <<endl;
}
return(0);
}

bool StringToInt(const string &s, int &i)
{
istringstream myStream(s);

if (myStream>>i)
return true;
else
return false;

/*
* Program output:
The string value is 12 and the int value is 12
Number conversion failed on ZZZ
*
*/

method 3 : The simpest method of all

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

string itos(int i)// convert int to string
{
stringstream s;
s << i;
return s.str();
}

int main()
{
int i = 127;
string ss = itos(i);
const char* p = ss.c_str();

cout << ss << " " << p << "\n";
}

KillingJoke2007-02-25T14:24:25Z

#include<stdlib.h>
...
for integer
itoa(int n,char* s);
for long
ltoa(long int n, char*s);