Tuesday, December 06, 2005

c++ Type Conversions

This will eventually come up in your programming days, so I thought I'd post it.

You need to convert a string input by the user to another data type (I'll use double here to demonstrate.)
//you'll need these includes
#include <string>
#include <sstream>

string s = "23.5"; // we need a string to work with
istringstream istr(s); // this is the stream we pump the string into (done by constructor)
double d; // a place to store the double we are asking for
istr >> d; // here we tell the sstream to pump our string out as a double

This can be easily formed into a function.
double toDouble(string& s) { // we only need a reference to the string since we are not going to modify it
istringstream istr(s);
double d;
istr >> d;
return d;
}

We can also reverse the process.
string toString(int& i) { // we only need a reference to the int since we are not going to modify it
ostringstream ostr;
ostr << fixed << i;
ostr << fixed << setw(8) << setprecision(3) << i;
// this second version adds some handy formatting
return ostr.str();
}

0 Comments:

Post a Comment

<< Home