C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

8. Interacting with Users


In This Chapter


  • Looking at scanf()

  • Prompting for scanf()

  • Solving problems with scanf()


printf() sends data to the screen. The scanf() function gets data from the keyboard. You must
have a way to get data from your user. You can’t always assign data values using assignment
statements. For example, if you were writing a movie theater program for use throughout the country,
you couldn’t assign the cost of a ticket to a variable using the equals sign in your program because
every theater’s ticket price could differ. Instead, you would have to ask the user of the program in
each theater location how much a ticket costs before computing a charge.


At first glance, the scanf() function might seem confusing, but it is so important to learn, to
increase the power of your programs through user interactivity. To a beginner, scanf() makes little
sense, but despite its strange format, it is the easiest function to use for input at this point in the book
because of its close ties to the printf() function. Practice with scanf() will make your
programs perfect!


Looking at scanf()


scanf() is a built-in C function that comes with all C compilers. Its header file is the same as
printf() (stdio.h), so you don’t have to worry about including an additional header file for
scanf(). scanf() fills variables with values typed by the user.


scanf() is fairly easy if you know printf(). scanf() looks a lot like printf() because
scanf() uses conversion codes such as %s and %d. scanf() is the mirror-image function of
printf(). Often you will write programs that ask the user for values with a printf() and get
those values with scanf(). Here is the format of scanf():


Click here to view code image


scanf(controlString [, data]);

When your program gets to scanf(), C stops and waits for the user to type values. The variables
listed inside scanf() (following the controlString) will accept whatever values the user
types. scanf() quits when the user presses Enter after typing values.


Even though scanf() uses the same conversion characters as printf(), never specify escape
sequences such as \n, \a, or \t. Escape sequences confuse scanf(). scanf() quits getting
values from the user when the user presses Enter, so you don’t ever specify the \n.


Prompting for scanf()


Almost every scanf() you write should be preceded with printf(). If you don’t start with a
printf(), the program stops and waits for input, and the user has no idea what to do. For example,

Free download pdf