CSC 161 Schedule Readings Labs & Projects Homework Deadlines Resources

Reading Data with scanf

Textbook Background

The C standard library allows us to read formatted data in much the same way we display it. The textbook provides background:

Introduction to scanf

The scanf function (in the stdio.h library) directs the machine to read values for one or more variables from the keyboard. For each desired value, scanf requires

Notes:

When a user enters information into a program, the user types a sequence of characters. Sometimes this information is intended to be a string of characters, such as a name or an address. In other applications, a sequence of characters, such as 123.45, should be interpreted as a number.

When characters are to be considered as numbers, input can follow either of two basic forms:

The library function scanf is commonly used for the latter approach. Using scanf involves several elements. The basics of this work are illustrated in the following code segment:

double a, b;
scanf  ("%lf", &a);
scanf  ("%lf", &b);

As illustrated in this segment,

scanf allows the two reading operations above to be combined within a single statement as follows:

double a, b;
scanf("%lf%lf", &a, &b);

Beyond the identification of variables and formats for reading, the scanf can specify other characters that must be part of the input. For example, suppose a program is supposed to read hours and minutes in the format hour:minutes:seconds, such as 12:34:56 or 5:8:27. In this setting, the user is supposed to enter the colon character between integer numbers. The following code segment would perform such a read operation:

int hr, min, sec;
scanf ("%d:%d:%d", &hr, &min, &sec);

A Note on Return Values

Note that scanf returns the number of input items assigned, which could be fewer than expected (even zero). Thus, it is generally useful (and highly recommended) to check the return value to make sure that your program received the amount of input it expected and take appropriate action if it did not.