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

else

print invalid vote

add 1 to spoiltVotes

endif

get a vote

endwhile

After all the votes are processed, this function will need to return the number of valid and

spoiled votes. But how can a function return more than one value? It can, if the values are stored

in a structure and the structure returned as the “value” of the function.

We will use the following declaration:

typedef struct {

int valid, spoilt;

} VoteCount;

298

And we will write processVotes as follows:

VoteCount processVotes(PersonData person[], int max, FILE *in, FILE *out) {

VoteCount temp;

temp.valid = temp.spoilt = 0;

int v;

fscanf(in, "%d", &v);

while (v != 0) {

if (v < 1 || v > max) {

fprintf(out, "Invalid vote: %d\n", v);

++temp.spoilt;

}

else {

++person[v].numVotes;

++temp.valid;

}

fscanf(in, "%d", &v);

} //end while

return temp;

} //end processVotes

Next, we write main, preceded by the compiler directives and the structure declarations.

#include <stdio.h>

#include <string.h>

#define MaxCandidates 7

#define MaxNameLength 30

#define MaxNameBuffer MaxNameLength+1

typedef struct {

char name[MaxNameBuffer];

int numVotes;

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!