[prev] 67 [next]

Sidetrack: Reading Variable Values with scanf() and atoi()

Formatted input read from standard input (e.g. keyboard)

scanf(format-string, expr1, expr2, …);

Converting string into integer

int value = atoi(string);

Example:

#include <stdio.h>   // includes definition of BUFSIZ (usually =512) and scanf()
#include <stdlib.h>  // includes definition of atoi()

...

char str[BUFSIZ];
int n;

printf("Enter a string: ");
scanf("%s", str);
n = atoi(str);
printf("You entered: \"%s\". This converts to integer %d.\n", str, n);

Enter a string: 9024
You entered: "9024". This converts to integer 9024.