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 10 ■ Structures

286

Suppose the data are stored in a file input.txt and in is declared as follows:

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

If str is a character array, assume we can call the function

getString(in, str)

to store the next data string in quotes in str without the quotes. Also assume that readChar(in)

will read the data and return the next non-whitespace character.

Exercise: Write the functions getString and readChar.

We can read the data into the array pupil with the following code:

int n = 0;

char temp[31];

getString(in, temp);

while (strcmp(temp, "END") != 0) {

strcpy(pupil[n].name, temp);

fscanf(in, "%d", &pupil[n].age);

pupil[n].gender = readChar(in);

n++;

getString(in, temp);

}

At the end, n contains the number of students stored, and pupil[0] to pupil[n-1] contain

the data for those students.

To ensure that we do not attempt to store more data than we have room for in the array, we

should check that n is within the bounds of the array. Assuming that MaxItems has the value 100,

this can be done by changing the while condition to the following:

while (n < MaxItems && strcmp(temp, "END") != 0)

or by inserting the following just after the statement n++; inside the loop:

if (n == MaxItems) break;

10.4 Search an Array of Structure

With the data stored in the array, we can manipulate it in various ways. For instance, we can write

a function to search for a given name. Assuming the data is stored in no particular order, we can

use a sequential search as follows:

int search(char key[], Student list[], int n) {

//search for key in list[0] to list[n-1]

//if found, return the location; if not found, return -1

for (int h = 0; h < n; h++)

if (strcmp(key, list[h].name) == 0) return h;

return -1;

} //end search

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!