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 ...
Get C Programming: Visual Quickstart Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.