CSC 161 Grinnell College Spring, 2010 Imperative Problem Solving and Data Structures

# Input and Output in C

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 program can proceed in two steps:

1. read the information as a sequence of characters
2. convert the character sequence to a number
• the program can rely upon a library function to perform both steps as one logical operation.

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,

• The first parameter for scanf indicates the format of data to be read.
• Use %lf for double precision real numbers (lf stands for "long float"),
• %f for single precision real numbers (floating point numbers), and
• %d for decimal integers.
• Use an ampersand & before the variable to represent the "address" of the variable (the location where the value should be stored).
• When reading a number, scanf skips initial whitespace (spaces, tabs, newline characters).
• After skipping whitespace, scanf reads as long a string of digits as it can to obtain a number. Thus, if one enters 123Walker, the scanf statement will read the number as 123; "Walker" is not part of a number, so reading of the number cannot proceed.
• If scanf tries to read a number but encounters non-numeric data after whitespace, then reading stops and the number is assigned the value 0.
• The above code segment skips whitespace (if any), reads a first number (up to whitespace or non-numeric data), and assigns the number read to variable a. This process then is repeated in reading variable b.

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);
```

This document is available on the World Wide Web as

```http://www.cs.grinnell.edu/~walker/courses/161.sp10/readings/reading-i-o.shtml
```