Thursday, March 11, 2010

Convert string to number in C++


There are several methods to convert a string to number in C++. We use floating point numbers as examples. There are similar functions for integer.

Method 1: use function atof().

The syntax of atof() is:
   #include <stdlib.h>
   double atof(const char *nptr);
The conversion code could be:
   const char *a = "234.5";
   double d;

   d = atof(a);
There is a little problem with this function. It does not detect errors. If it can not convert the string, it returns 0. By examing the return value, you can not know whether it has encountered errors or the string is "0".

Method 2: use function strtod().

The syntax of strtod() is:
   #include <stdlib.h>
   double strtod(const char *nptr, char **endptr);
The conversion code could be:
   const char *a = "234.5";
   double d;
   char *b;

   d = strtod(a, &b);
   if (0 == d && a == b) {
      // error handling.
   }
strtod() is similar to atof() except that it detects errors. If errors occur, it returns 0 and set pointer b (the second parameter) to the value of a (the first parameter).

Method 3: use function sscanf().

The syntax of sscanf() is:
   #include <stdio.h>
   int sscanf(const char *str, const char *format, ...);
The conversion code could be:
   const char *a = "234.5";
   double d;
   int r;

   r = sscanf(a, "%lf", &d);
   if (r <= 0) {
      // error handling.
   }
sscanf() returns the number of items converted. So if it returns 0, it means it can not do the conversion. If it returns -1 (EOF), it means there is no more input.

Method 4: use stream.

We use the istringstream class. This method is more OO-style.
   #include <sstream>

   const char *a = "234.5";
   double d;

   istringstream iss(a);
   iss >> d;
   if (iss.bad() || iss.fail()) {
      // error handling.
   }

No comments:

 
Get This <