Input of items in C

For the first time we are using numerical data as input to this program. To read it in we use the standard input function scanf.

The function getchar

Corresponding to putchar there is a function char getchar(void); This reads in the next character, printing or non-printing, from the input stream and returns its internal character code, which is an int restricted to the range 0..255.

The function scanf

Matching printf is an input function int scanf(const char*, ...). The value returned tells us how successful it has been in carrying out our intentions. We often use it as a procedure , but this may be unsafe if the input data is not in the expected format.

Like printf, scanf requires a format string as its first parameter and will then expect a list of parameters, one for each format specifier embedded in this string. These parameters should be pointers to variables of the required type, given in the same order. The formats specified are the same as those for printf, %d, %c etc. Thus, each format string defines a pattern that will be looked for in the input stream. If a match for this pattern is found, the value of the item matching each format specifier will be stored in the required internal form in the variable pointed to by the matching parameter.

Thus the program

#include <stdio.h>

void main()
{
   int i1;
   char c1;
   float f1;
   char s1[6];
   scanf("int %d char %c float %f string %s\n",
                                          &i1, &c1, &f1, s1);
}
will input the line
int 3 char e float 3.4 string yes
and store the value 3 in i1, 'e' in c1, 3.4 in f1 and "yes" in s1. Plain text to compile.

Exercises on this section.


Next - format specifiers.

Back to Input and Output.

Back to Contents page.