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

(Romina) #1

and recompile and run the program. You will find the prompt confusing, and you wrote the program!
Think of how the user will feel.


The first two scanf() statements obtain character values (as you can tell from the %c conversion
codes). The third scanf() gets an integer value from the keyboard and places it into a variable
named age.


The variables firstInitial, lastInitial, and age will hold whatever the user types before
pressing Enter. If the user types more than a single character in the first two examples, it can confuse
the program and create problems for the later values.


Another point to notice about the scanf() statements is the spaces right before each %c or %d. The
space isn’t always required here, but it never hurts, and it sometimes helps the input work better when
you get numbers and characters in succession. Adding the extra space is a good habit to get into now
while learning scanf().


Enough about all that. Let’s get to the most obvious scanf() problem: the ampersand (&) before the
three variables. Guess what? scanf() requires that you put the ampersand before all variables,
even though the ampersand is not part of the variable name! Do it, and scanf() works; leave off the
ampersand, and scanf() won’t accept the user’s values into the variables.


Tip

Make your leading printf() statement as descriptive as possible. In the last
example, if you ask for only a favorite number, a user might enter a decimal instead of
just a whole number. Who knows—maybe someone’s favorite number is 3.14159.

Problems with scanf()


As mentioned earlier in this chapter, scanf() is not the easiest function to use. One of the first
problems with scanf() is that although the user must type exactly what scanf() expects, the user
rarely does this. If the scanf() needs a floating-point value, but the user types a character, there is
little you can do. The floating-point variable you supply will have bad data because a character is not
a floating-point value.


For now, assume that the user does type what is needed. Chapter 18, “Increasing Your Program’s
Output (and Input),” describes some ways to overcome problems brought on by scanf() (although
modern-day C programmers often resort to complete data-entry routines they write, download, or
purchase elsewhere that overcome C’s difficult data-entry ability).


An exception to the ampersand rule does exist. If you’re getting input into an array using %s, as
happens when you ask users for a name to be stored in a character array, you do not use the
ampersand.


The bottom-line rule is this: If you’re asking the user to type integers, floating points, characters,
doubles, or any of the other single-variable combinations (long integers and so on), put an ampersand
before the variable names in the scanf(). If you are asking the user for a string to input into a

Free download pdf