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 8 ■ Arrays

If n is not a value from 1 to 7, the function stores Invalid day in name. If it is a valid day

number, it stores the value of day[n] in name. For example, if n is 6, the function stores day[6],

that is, Friday, in name.

In main, dayName is declared to be of size 12 since it needs to hold the string "Invalid day" if

the day number is invalid.

8.11 A Flexible getString Function

So far, we have used the format specification %s to read a string containing no whitespace

characters and the function gets to read a string up to the end-of-line. However, neither of these

allows us to read a string delimited by double quotes, for instance. Suppose we had data as in the

following format:

"Margaret Dwarika" "Clerical Assistant"

We would not be able to use %s or gets to read this data easily.

We will write a function, getString, which lets us read a string enclosed within ‘delimiter’

characters. For example, we could specify a string as $John Smith$ or "John Smith." This is a very

flexible way of specifying a string. Each string can be specified with its own delimiters which could

be different for the next string. It is particularly useful for specifying strings which may include

special characters such as the double quotes without having to use an escape sequence like\".

For instance, in order to specify the following string in C:

"Don't move!" he commanded.

we must write:

"\"Don't move!\" he commanded."

228

With getString, this string could be supplied as

$"Don't move!" he commanded.$

or

%"Don't move!" he commanded.%

or using any other character as a delimiter, provided it is not one of the characters in the string.

We could even use something like this:

7"Don't move!" he commanded."7

but would normally use special characters like ", $, % or # as delimiters.

We will write getString with two parameters: a file designated by in and a character

array str. The function will read the next string from in and store it in str.

The function assumes that the first non-whitespace character met (delim, say) is the

delimiter. Characters are read and stored until delim is met again, indicating the end of the string.

The delimiter characters are not stored since they are not part of the string.

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!