// The pizza topping is a string, so your scanf doesn't need an &
printf("What is your favorite one-word pizza topping?\n");
scanf(" %s", topping);
printf("How many slices of %s pizza", topping);
printf("can you eat in one sitting?\n");
scanf(" %d", &slices);
printf("What is today's date (enter it in XX/XX/XX format).\n");
scanf(" %d/%d/%d", &month, &day, &year);
printf("\n\nWhy not treat yourself to dinner on %d/%d/%d",
month, day, year);
printf("\nand have %d slices of %s pizza!\n", slices, topping);
printf("It will only cost you $%.2f!\n\n\n", cost);
return (0);
}
The format and use of scanf() statements will become easier with practice. If the user wanted to
enter a two-word topping, like Italian sausage, your program would need two scanf() statements
to capture them and two variables to save the names. Later in the book, you learn some tricks to ask
your users for multiple pieces of data instead of just one within a particular category.
Again, use your printf() statements to more effectively guide users to enter data in a format that
your program needs. Try entering information incorrectly when running this program, such as leaving
off the dollar sign on the pizza price or forgetting the slashes in the date, and you will see the
problems you can create for your program.
Tip
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. In the previous
example, if the user doesn’t type in the dollar sign before the price of the pizza, the
program will not function properly. The following scanf() that gets a date expects
the user to type the date in mm/dd/yy format:
Click here to view code image
scanf(" %d/%d/%d", &month, &day, &year);
The user could type 02/28/14 or 11/22/13, but not June 5th, 2013, because
the scanf() is expecting something else.
The Absolute Minimum
This chapter’s goal was to teach you how to ask for and get answers from the user.