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.clear();
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.clear();
ss << s; //write the string to stringstream
ss >> n; //read back the value as an int
cout << "int value: " << n << endl;

}

Have fun!

3 comments:

Sohel said...

#include?

Sohel said...

#include<sstream>

Sohel said...

#include<sstream>