08.01.2023 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8 ■ Arrays

Suppose we have the following declarations in main:

FILE * input = fopen("quizdata.txt", "r");

char country[50];

and the file quizdata.txt contains strings delimited as described above. We would be able to

read the next string from the file and store it in country with this:

getString(input, country);

It is up to us to ensure that country is big enough to hold the next string. If not, the program

may crash or nonsense results will occur.

Here is getString:

void getString(FILE * in, char str[]) {

//stores, in str, the next string within delimiters

// the first non-whitespace character is the delimiter

// the string is read from the file 'in'

char ch, delim;

int n = 0;

str[0] = '\0';

// read over white space

while (isspace(ch = getc(in))) ; //empty while body

if (ch == EOF) return;

delim = ch;

while (((ch = getc(in)) != delim) && (ch != EOF))

str[n++] = ch;

str[n] = '\0';

} // end getString

Comments on getString

• The predefined function isspace returns 1 (true) if its char argument is a

space, tab, or newline character and 0 (false), otherwise.

• If getString encounters end-of-file before finding a non-whitespace

character (the delimiter), the empty string is returned in str. Otherwise, it

builds the string by reading one character at a time; the string is terminated

by the next occurrence of the delimiter, or end-of-file, whichever comes first.

• We can read a string from the standard input (the keyboard) by calling

getString with stdin as the first argument.

229

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!