8. Can I Ask the User Questions?

With scanf()

image

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 video rental program for use throughout the country, you couldn’t assign the cost of a tape rental to a variable using the equals sign in your program because every store’s rental could differ. Instead, you would have to ask the user of the program in each store location how much a tape rental costs before computing a charge.

You won’t like learning scanf(), so we might as well get it over with as soon as possible. You will find that scanf() is the craziest function that could possibly exist! 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.

Looking at scanf()

Figure 8.1 shows you what scanf() does. 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().

Figure 8.1. scanf() fills variables with values typed by the user.

image

Note

image

scanf() is fairly easy if you know printf(). scanf() looks a lot like printf() because scanf() uses conversion codes such as %s and %d.

Clue

image

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():

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.

Prompting for scanf()

Almost every scanf() you write should be preceded with printf(). If you don’t issue a printf(), the program will stop and wait for input, and the user will have no idea what to do. For example, if you need to get an amount from the user, you would put a printf() function like this before scanf():

printf("What is the amount? ");  /* Prompt */
/* A scanf() would follow */

Clue

image

A printf() before a scanf() sends a prompt to the user. If you don’t prompt the user for the value or values you want, the user has no way of knowing what values should be typed. Generally, the printf() requests the data from the user and the scanf() gets the data that the user types.

Problems with scanf()

As mentioned in the first part of this chapter, scanf() is not the easiest function in the world 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, “How Can I Control Input and Output?,” 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 overcomes C’s difficult data-entry ability).

Here is a scanf() that gets an integer value (as you can tell from the %d integer conversion code) from the keyboard into a variable named age:

scanf(" %d", &age);

The variable age will hold whatever number the user types before pressing Enter.

The first thing to notice about scanf() is the space right before the %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 variable age. 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.

Clue

image

There is an exception to the ampersand rule you should know about. 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 into a character array, don’t put the ampersand before the array name.

Warning

image

You also wouldn’t put the ampersand in front of pointer variables. Actually, an array is nothing more than a pointer variable, and that’s why the ampersand isn’t needed for arrays. We’ll get to pointers later in this book, but if you’ve seen them in other languages, you know what I’m talking about. If you haven’t seen a pointer variable before, and you don’t know what this is all about, well, you were warned not to read this paragraph anyway! Seriously, you’ll fully understand pointers and how they are like arrays after reading Chapter 25, “How Are Arrays and Pointers Different?”

Note

image

There’s a problem with using scanf() to get character strings into character arrays that you should know about now. scanf() stops reading string input at the first space. Therefore, you can get only a single word at a time with scanf(). If you must ask the user for more than one word, such as the user’s first and last name, use two scanf()s (with their own printf() prompts) and store the two names in two character arrays.

The following program asks the user for a first name, last name, age, and weight. Notice that the character arrays have no ampersands, but that the other two variables do. The program doesn’t ask for the user’s full name because scanf() isn’t capable of getting two words at once.

image

Here is a sample execution of this program:

image

Clue

image

You can let the user type characters other than data values. For example, many times dates are entered with slashes or hyphens separating the day, month, and year like this: 03/05/95. You have to trust the user to type things just right. Here is a scanf() that gets a date and expects the user to type the date in mm/dd/yy format:

scanf(" %d/%d/%d", &month, &day, &year);

The user could type 02/28/94 or 11/22/95 but not June 5th, 1993 because the scanf() is expecting something else.

Rewards

image

• Use scanf() if you want to get data from the user by way of the keyboard.

• Every scanf() requires a control string that dictates how your data will look when input.

• Before using a scanf(), use a printf() to prompt the user for the values you want.

• Put an ampersand before non-array variables in a scanf().

Pitfalls

image

• Don’t forget to put a space before the first control string character (for example, " %d" contains a space before the %) to ensure accurate input.

• Don’t use an ampersand in front of array names in a scanf().

Don’t expect the user to type exactly what you want! If exact accuracy is needed, such as in an end-user environment where noncomputerists will be using your program, you’ll want to use other means of input that are explained in Chapter 18, “How Else Can I Control Input and Output?”

In Review

This chapter’s goal was to teach you how to ask for and get answers from the user. Being able to process user input is an important part of any language. scanf() performs data-entry; that is, scanf() gets the user’s input and stores that input in variables.

Before using a scanf(), you will need to let the user know what kind of keyboard input you’re expecting. For example, before using scanf() to get a sales amount, use a printf() to ask for the amount so the user knows what to type.

Although scanf() uses the same format codes as printf(), scanf() has extra requirements that you should understand. scanf() requires an & in front of non-array variables. Also, if you are getting strings from the user, the scanf() and %s combination can get only one word at a time.

Code Example

image

Code Analysis

These lines of code prompt the user with a printf() before each scanf(). With the printed prompts, the user knows exactly what is required. The format code must match the variable’s data type. Earlier in the program, the variables homeTown and state must have been defined as character arrays because they are to hold strings. The variable yearBorn is an int data type. (int is a large enough data type to hold year values.)

Because the first two variables are arrays, no ampersand is needed before them in the scanf()s. An & is needed before non-array variables such as yearBorn.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset