String to Number Conversions in C

Numbers can be stored either as strings or in numeric form. Storing a number as a string means storing the digit characters. For example, the number 213 can be stored in a character string array as the digits ‘2’, ‘1’, ‘3’, ‘\0’. Storing 213 in numeric form means storing it as, say, an int.

C requires numeric forms for numeric operations, such as addition and comparison, but displaying numbers on your screen requires a string form because a screen displays characters. The printf() and sprintf() functions, through their %d and other specifiers, convert numeric forms to string forms, and vice versa. C also has functions whose sole purpose is to convert string forms to numeric forms.

Suppose, for example, that you want a program to use a numeric command-line argument. Unfortunately, command-line arguments are read as strings. Therefore, to use the numeric value, you must first convert the string to a number. If the number is an integer, you can use the atoi() function (for alphanumeric to integer). It takes a string as an argument and returns the corresponding integer value. Following program shows a sample use.


#include <stdio.h>

int main()
    char a[]="123";
    int ab = atoi(a);
    printf("in numbers = %d",ab);
    printf("\nafter one increment = %d",ab);
    return 0;