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

Putting all the pieces together, we get Program P10.2, the program to solve the voting problem.

Program P10.2

#include <stdio.h>

#include <string.h>

#define MaxCandidates 7

#define MaxNameLength 30

#define MaxNameBuffer MaxNameLength+1

typedef struct {

char name[MaxNameBuffer];

int numVotes;

} PersonData;

PersonData candidate[MaxCandidates];

typedef struct {

int valid, spoilt;

} VoteCount;

int main() {

void initialize(PersonData[], int, FILE *);

VoteCount processVotes(PersonData[], int, FILE *, FILE *);

void printResults(PersonData[], int, VoteCount, FILE *);

PersonData candidate[MaxCandidates+1];

VoteCount count;

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

FILE *out = fopen("results.txt", "w");

initialize(candidate, MaxCandidates, in);

count = processVotes(candidate, MaxCandidates, in, out);

printResults(candidate, MaxCandidates, count, out);

fclose(in);

fclose(out);

} //end main

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

301

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!