08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3 ■ Programs with Sequence Logic

The first scanf will store 4000 in item. On completion, it remains poised at the space after

4000. The next scanf will continue reading from that point and will store 7.99 in price. This

scanf will stop at the space after 7.99. The third scanf will continue reading from that point

and store 8 in quantity. This scanf will stop at the character after 8; this may be a space or the

end-of-line character. Any subsequent scanf will continue reading from that point.

It is useful to imagine a “data pointer” moving through the data as data items are read. At any

time, it marks the position in the data from which the next scanf will start looking for the next

item of data.

3.4 Read Strings

In Section 2.6, we saw how to declare a variable to hold a string value. For example, the

declaration

char item[50];

lets us store a string value (of maximum length 49) in item. We also saw how we can assign a

string value to item using the standard string function, strcpy.

Now we show you how to read a value from the input into item. There are several ways to do

this in C. We will use the gets (usually pronounced get s not gets) statement (more precisely, a

function), as in:

gets(item);

This reads characters and stores them in item starting from the current position of the data

pointer until the end-of-line is reached. The end-of-line character is not stored. The data pointer

is positioned at the beginning of the next line.

For example, if the data line is

Right front headlamp

then the string Right front headlamp is stored in item. The effect is the same as if we had written

strcpy(item, "Right front headlamp");

The alert reader will notice that we did not put an & before item, as we have been doing for

reading numbers with scanf. For now, just note that item is a “character array” and the rule in C

is that we must not put & before an array name when reading data into it. You may understand

this better after we discuss arrays in Chapter 8. The quick explanation is that an array name

denotes the “address of the first element of the array” so there is no need for & to get the address.

For now, just think of it as a rule that you need to follow.

Consider the following statements (assume the declaration char name[50]):

printf("Hi, what's your name? ");

gets(name);

printf("Delighted to meet you, %s\n", name);

54

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!