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!

C++: Failed Conditions

At ReliSource, we used to have a mailing list called CPP in which we submitted C/C++ related facts/questions (and solutions). I'll share some of those facts/questions in my blog.

Here goes a quick C/C++ problem that I'm sure you will find interesting.

// x is a numeric variable (of built in/intrinsic data type).

if (x > 10)
{
cout << "x is > 10\n";
}
else if (x <= 10)
{
cout << "x is <= 10\n";
}

For some reason, the program didn't output anything, none of the if or else-if was executed. What can be the reason?

You shall find the answer in the comments after a week of this post (if someone already doesn't answer it).