In a local government meeting, community leaders are required to identify one SDG, out of the 17 goals, that is most important to local PNG communities. Each community leader is required to select their goal of choice only once. The vote is recorded as a number from 1 to 17. The number of community leaders voting is unknown beforehand, so the votes are terminated by a value of zero (0). Votes not within and not inclusive of the numbers 1 to 17 are invalid (spoilt) votes. A file, sdGoals.txt contains the list of goals. The first goal is listed as SDG 1, the second as SDG 2 and so forth. The goals are followed by the number of votes for the goal.
Write a program to read the data and evaluate the results of the selection. Print all the output to a file called sdgSelection.txt
The program output should specify the total number of votes and the number of invalid votes. This is followed by the votes received for each SDG and the winning (top) selection SDG.
#include <stdio.h>
#include <string.h>
#define N 17
#define LEN 100
int main() {
FILE *fg;
FILE *fs;
char goals[N][LEN];
int votes[N] = {0};
int vote, n_votes=0, n_incorr=0;
int top;
int i;
fg = fopen("sdGoals.txt", "r");
for (i=0; i<N; i++) {
int len;
fgets(goals[i], LEN, fg);
len = strlen(goals[i]);
if (goals[i][len-1] == '\n') {
goals[i][len-1] = '\0';
}
}
fclose(fg);
while (1) {
printf("Enter a vote: ");
scanf("%d", &vote);
if (vote == 0) {
break;
}
n_votes++;
if (vote < 0 || vote > N) {
n_incorr++;
}
else {
votes[vote-1]++;
}
}
top = 0;
for (i=1; i<N; i++) {
if (votes[top] < votes[i]) {
top = i;
}
}
fs = fopen("sdgSelection.txt", "w");
fprintf(fs, "Total number of votes: %d, invalid votes: %d\n",
n_votes, n_incorr);
for (i=0; i<N; i++) {
fprintf(fs, "%s - %d\n", goals[i], votes[i]);
}
fprintf(fs, "The winning is goal %s\n", goals[top]);
return 0;
}
Comments
Leave a comment