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 the inputted text should be assigned. The second argument dictates how many characters should be read, as a maximum value. The most flexible way to set this is to use the sizeof() function, which returns the length of a variable. So if input is set to be up to 10 characters long, fgets() should read up to 9 characters from the keyboard (the tenth character will be the terminating