Numeric conversion

How to convert int into string ?
I had done conversion string to int.
My code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*Convert string into int using stringstream */
#include <iostream>
#include <string>
#include "console.h"
#include <sstream>
using namespace std;
int main() {
string text;
cout << " String2Int : " ;
	cin >> text;
	
	int Number; 
	if ( !(istringstream(text) >> Number) ) { //give the value to Number(int)
		Number = 0; //Set Number=0 if fail
		cout << " Failed to convert ! "<< endl;
	}else{
		cout << "Conversion Complete ! "<<endl;
	} 
}


Keeping it reasonably simple:

1
2
3
4
5
6
std::string ToString( int n )
{
  std::stringstream s;
  s << n;
  return s.str();
}


If you're using a C++11 compliant compiler, you can use the to_string function.
Also:

 
string = boost::lexical_cast<std::string>(n);
That requires boost, which is an order of magnitude harder to install than a C++11 compiler for a beginner.
Last edited on
Topic archived. No new replies allowed.