Guides:C/C Crash Course/Converting text to and from numbers

From CoderGuide

Jump to: navigation, search

Back to TOC

Converting text to numbers

Every now and then, we may want to convert a text string to a number. C has a few very useful functions for doing this. They are pretty straight forward, and, you should know enough about C now to know how to use the from their function prototypes:

int atoi(char *)
long atol(char *)
long long atoll(char *) for C99 compliant compilers.
double atof(char *)

There are other ways, but these are the easiest, and most useful functions to use. the strtol(), strtod(), strtoll(), strtold(), strtof() and other like-named functions, allow for more options. They take the form of:

float strtof(const char *nptr, char **endptr);
long int strtol(const char *nptr, char **endptr, int base);

Some of these functions are described by the ANSI C standard, others, including stroll() and atoll() are defined by the ISO C99 and POSIX.1 (1996) standards. In order to use these functions, you need to also include the stdlib.h header file.

Personal tools