Monday, June 21, 2010

C++: Convert string to int or vice-versa

strinstream is very useful for many basic jobs with strings, for example parsing numeric data from a string, converting a string to int/float, converting int/float to string, etc.

Here goes examples of how to use stringstream to convert to and from strings.

#include <iostream>
#include <sstream>

using namespace std;

int main()
stringstream ss;
string s;
int n;

//to convert int to string
n = 1024;

ss << n; //write the int to stringstream
ss >> s; //read back the value as a string
cout << "string value: " << s << endl;

//to convert int to string
s = "2048";

ss << s; //write the string to stringstream
ss >> n; //read back the value as an int
cout << "int value: " << n << endl;


Have fun!


Sohel said...


Sohel said...


Sohel said...