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

Here, candidate is an array of structures. We will use candidate[1] to candidate[7] for the

seven candidates; we will not use candidate[0]. This will allow us to work more naturally with

the votes. For a vote (v, say), candidate[v] will be updated. If we use candidate[0], we would

have the awkward situation where for a vote v, candidate[v-1] would have to be updated.

An element candidate[h] is not just a single data item but a structure consisting of two fields.

These fields can be referred to as follows:

candidate[h].name and candidate[h].numVotes

To make the program flexible, we will define the following symbolic constants:

#define MaxCandidates 7

#define MaxNameLength 30

#define MaxNameBuffer MaxNameLength+1

We also change the earlier declarations to the following:

typedef struct {

char name[MaxNameBuffer];

int numVotes;

} PersonData;

PersonData candidate[MaxCandidates+1];

The solution is based on the following outline:

initialize

process the votes

print the results

The function initialize will read the names from the file in and set the vote counts to 0.

The file is passed as an argument to the function. We will read a candidate’s name in two parts

(first name and last name) and then join them together to create a single name that we will store

in person[h].name. Data will be read for max persons. Here is the function:

void initialize(PersonData person[], int max, FILE *in) {

char lastName[MaxNameBuffer];

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

fscanf(in, "%s %s", person[h].name, lastName);

strcat(person[h].name, " ");

strcat(person[h].name, lastName);

person[h].numVotes = 0;

}

} //end initialize

Processing the votes will be based on the following outline:

get a vote

while the vote is not 0

if the vote is valid

add 1 to validVotes

add 1 to the score of the appropriate candidate

297

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!