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 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 ). The third argument (stdin) tells fgets() from which file the string should be read. In this case, the file is stdin, the standard input (the keyboard).

The second function in this code—sscanf()—converts a string to another data type. It uses the same signifiers as printf() and scanf(). The first argument is the existing string (input), the second is the formatting, and the third is the variable to which the value should be assigned. The variable's name is preceded by the ampersand so that the address of the variable is referenced. Again, you'll better understand this concept in Chapter 9.

To demonstrate reading in numeric input, let's write another temperature-conversion application, this time converting a user-submitted temperature from Celsius to Fahrenheit.

To read in numeric input

1.
Create a new file or project in your text editor or IDE.

2.
Type the standard beginning lines of code (Script 5.3):

/* c_to_f.c - Script 5.3 */
#include <stdio.h>
int main (void) {

Script 5.3. Two functions are used to read in numeric input, which will then be used in a calculation.


3.
Declare the required variables:

float temp_f, temp_c;
char input[10];

This application has three variables. The first two are floats, for the temperature in degrees Fahrenheit and Celsius. The third is a character string that will store the inputted text (that the user types into the keyboard).

4.
Prompt the user and read in the input:

printf ("Enter a temperature in
 degrees Celsius: ");
fgets (input, sizeof(input)-1, stdin);
sscanf (input, "%f", &temp_c);

Following the syntax outlined earlier, the fgets() function will read in up to 9 characters (which is the value of sizeof(input) minus the one required for the ) from the standard input (the keyboard). The sscanf() function will then convert this to a float, which is assigned to the temp_c variable.

5.
Convert the temperature:

temp_f = temp_c * 9.0/5.0 + 32;

This is the same formula that has been used earlier in the book.

6.
Print the results:

printf ("%0.1f degrees Celsius is
 %0.1f degrees Fahrenheit.
",
 temp_c, temp_f);

Both the initial and calculated temperatures will be printed. The formatting specifies that they are printed with one decimal point.

7.
Complete the main function:

      getchar();
      getchar();
      return 0;
}

8.
Save the file as c_to_f.c, compile, and debug as necessary.

9.
Run the application to see the results (Figure 5.7).

Figure 5.7. The submitted temperature in degrees Celsius is converted into Fahrenheit and then both values are printed.


✓ Tips

  • If a non-numeric value is entered (Figure 5.8), you'll see different results based on your development environment. The “Validating Keyboard Input” section of this chapter will show how to first validate data before using it in calculations.

    Figure 5.8. If you enter characters instead of a number value, you'll see odd results as the sscanf() function will not be able to create a float value from a character string.

  • The fgets() function will read either sizeof(input)-1 characters or until a newline ( ) character, whichever comes first. If it does read in a newline, that will also be assigned to the input variable.

  • The fgets() with sscanf() method can be used to read in any variable type, although getchar() works just fine for characters and scanf() is good with strings.

  • The fgets() function is also used for reading from files, as you'll see in Chapter 12.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset