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

(Romina) #1

character array, don’t put the ampersand before the array name.


Warning

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 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 and you don’t
know what this is all about, well, I promise you’ll get there soon! Seriously, you’ll
fully understand pointers and how they are like arrays after reading Chapter 25,
“Arrays and Pointers.”

There’s a problem with using scanf() to get character strings into character arrays that you need to
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() statements (with their own printf() prompts) and
store the two names in two character arrays.


The following program uses scanf() statements to ask the user for a floating point (the price of a
pizza), a string (a pizza topping), and several integers (number of pizza slices and the month, day, and
year). Notice that the string has no ampersand, but the other variables do. The program asks for only a
one-word pizza topping because scanf() isn’t capable of getting two words at once.


Click here to view code image


// Example program #2 from Chapter 8 of Absolute Beginner's Guide to
// C, 3rd Edition
// File Chapter8ex2.c
/* This is a sample program that asks users for some basic data and prints it on
screen in order to show what was entered */
#include <stdio.h>

main()
{
char topping[24];
int slices;
int month, day, year;
float cost;
// The first scanf will look for a floating-point variable, the cost
// of a pizza
// If the user doesn't enter a $ before the cost, it could cause
// problems
printf("How much does a pizza cost in your area?");
printf("enter as $XX.XX)\n");
scanf(" $%f", &cost);
Free download pdf