Bringing Information into C Programs

The printf function has a complement in the scanf function. scanf reads information into a program. For example,

main()
{
   int num_stud ;

   printf( "How many students? " ) ;
   scanf( "%d", &num_stud ) ;
   printf( "There are %d students.\n", num_stud ) ;
}

scanf() is like printf() in that it takes a format string and then zero or more arguments identifying where to put the information. Also like printf(), the format string for scanf() specifies the format for all inputs to be read by that call. So if you have several variables being read by the same call to scanf(), you'll have several format specifiers (like the %d) in the format string. As in this example, we rarely have anything except the format specifiers in a scanf() format string. Here the %d indicates that we'll be expecting a decimal integer much as it did in printf(). Another thing to notice is that we must specify a variable as the place to put the result; we can't (normally) use a more complicated expression. Finally, notice that we precede the variable name by the character &. For now, just remember that when you are using scanf(), you need to precede any numeric variables by an ampersand (&). (The real reasons will become clear in Parts 2 and 6.)

Enter a scanf statement that will read decimal integers into two variables called foo and bar.