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

We could even separate the list into male and female students by sorting on the gender field.

Since F comes before M in alphabetical order, we can put the females first by writing this:

while (k >= 0 && temp.gender < list[k].gender)

//move Fs to the left

And we can put the males first by writing this:

while (k >= 0 && temp.gender > list[k].gender)

//move Ms to the left

10.6 Read, Search, and Sort a Structure

We illustrate the ideas discussed earlier by writing Program P10.1. The program performs the

following:

• Reads data for students from a file, input.txt, and stores them in an array of

structures.

• Prints the data in the order stored in the array.

• Tests search by reading several names and looking for them in the array.

• Sorts the data in alphabetical order by name.

• Prints the sorted data.

The program also illustrates how the functions getString and readChar may be written.

getString lets us read a string enclosed within any “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 that may include special characters such as

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

Program P10.1

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <ctype.h>

#define MaxStudents 100

#define MaxNameLength 30

#define MaxNameBuffer MaxNameLength+1

typedef struct {

char name[MaxNameBuffer];

int age;

char gender;

} Student;

288

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!