O'Reilly logo

C Programming: Visual Quickstart Guide by Marc Liyanage, Larry Ullman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reading Numeric Input

The previous two examples read in a single character and then an entire string. But what if you want to read in numeric input? For this, you can again use the scanf() function:

int age;
printf ("Enter your age: ");
scanf ("%d", &age);

This method generally works and has the added benefit of familiarity. Unfortunately, this function can be unreliable in properly handling numeric input (although it's still commonly used). A better solution—which is really a kludge (an inelegant solution)—uses the fgets() and sscanf() functions:

int age;
char input[10];
printf ("Enter your age: ");
fgets (input, sizeof(input)-1, stdin);
sscanf (input, "%d", &age)

With the fgets() function, the first argument (input) tells C to which variable ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required