Home > C++, VC++ > Converting a string to number and vice versa

Converting a string to number and vice versa

There are standard C functions which helps us in this. Some are listed below, and they are quite easy to use!

  • strtol, strtoul – Function to convert a string to integer, also converts numbers in different bases for e.g. hex, oct, decimal
  • strtod – Function to convert a string to double
  • atoi, wtoi, _ttoi – Converts string to integer
  • itoa, itow, _ttoa – Integer to string
  • atof, wtof, _ttof – Converts string to double
  • _atodbl, _atodbl_l, _atoldbl, _atoldbl_l, _atoflt _atoflt_l – Same as above except for float and long double version
  • ftoa, ftow, _ttow – Converts double to string
  • stringstream – Insert a double or any number and then call StrStreamObj.str() function to get it’s string form or another way is to use input/output redirection operators.
  • sprintf,_stprintf
  • _gcvt, _fcvt

Code snippet on how to use stringstream to convert strings to numbers and vice versa

// Convert string to double
std::stringstream sstream;
sstream < < "23423.8980";
double dbl = 0.0;
sstream >> dbl;

// Convert double to string
std::stringstream sstream;
sstream < < std::setprecision( 10 );
char chConv&#91;20&#93; = { 0 };
double dbl = 12312.698;
sstream << dbl;
sstream >> chConv;
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: