C - Strings Converting to Numerical Values

Introduction

The stdlib.h header file has the following functions that you can use to convert a string to a numerical value.

The functions requires an argument that's a pointer to a string or an array of type char containing a string representing a numerical value.

Function
Returns
atof()


convert string to type double. Infinity as a double value is
recognized from the strings "INF" or "INFINITY" where any character can be in uppercase or
lowercase and 'not a number' is recognized from the string "NAN" in uppercase or lowercase.
atoi()
convert string to type int
atol()
convert string to type long
atoll()
convert string to type long long

For all four functions, leading whitespace (isspace() returns true) is ignored.

Any characters following the character representation of the value that cannot form part of the value are also ignored.

char value_str[] = "12.4";
double value = atof(value_str);         // Convert string to floating-point

The following functions convert substrings to floating-point values.

Function
Returns
strtod()
convert substring to type double
strtof()
convert substring to type float.
strtold()
convert substring to type long double.

These functions recognize "INF", "INFINITY", and "NAN".

They will recognize floating-point values with or without an exponent in decimal or hexadecimal form.

A hexadecimal value must be preceded by 0x or 0X.

Here's how you might convert several substrings from a single string to double values:

double value = 0;
char str[] = "1.5 1.5 1.26";     // The string to be converted
char *pstr = str;                // Pointer to the string to be converted
char *ptr = NULL;                // Pointer to character position after conversion
while(true)
{
  value = strtod(pstr, &ptr);    // Convert starting at pstr
  if(pstr == ptr)                // pstr stored if no conversion...
    break;                       // ...so we are done
  else
  {
    printf("  %f", value);       // Output the resultant value
    pstr = ptr;                  // Store start for next conversion
  }
}

strtoll(), strtoul(), and strtoull() convert a substring to a value of type long long, unsigned long, and unsigned long long, respectively.


char str[] = "123  234  0xAB    111011";
char *pstr = str;
char *ptr = NULL;
long a = strtol(pstr, &ptr, 0);            // Convert base 10 value       a = 123
pstr = ptr;                                // Start is next character
unsigned long b = strtoul(pstr, &ptr, 0);  // Convert base 10 value       b = 234L
pstr = ptr;                                // Start is next character
long c = strtol(pstr, &ptr, 16);           // Convert a hexadecimal value c = 171
pstr = ptr;                                // Start is next character
long d = strtol(pstr, &ptr, 2);            // Convert binary value        d = 59