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

int n = 0;

getString(in, temp);

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

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

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

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

n++;

getString(in, temp);

}

return n;

} //end getData

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

void sort(Student list[], int n) {

//sort list[0] to list[n-1] by name using an insertion sort

Student temp;

int k;

for (int h = 1; h < n; h++) {

temp = list[h];

k = h - 1;

while (k >= 0 && strcmp(temp.name, list[k].name) < 0) {

list[k + 1] = list[k];

k = k - 1;

}

list[k + 1] = temp;

} //end for

} //end sort

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;

290

delim = ch;

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

str[n++] = ch;

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!