From fa0f26fda1755abb376fe16f9003d21ca85fb01a Mon Sep 17 00:00:00 2001 From: ak643du Date: Thu, 21 Mar 2024 16:51:55 +0100 Subject: [PATCH] Initialization --- cv5/program.c | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/cv5/program.c b/cv5/program.c index ad3bb6e..3c66a1a 100644 --- a/cv5/program.c +++ b/cv5/program.c @@ -42,14 +42,31 @@ int main() { // parse the string and extract number of votes and student name int votes; - if (sscanf(line, "%d %[^\n]", &votes, students[size].name) != 2) { + char name[SIZE]; + if (sscanf(line, "%d %[^\n]", &votes, name) != 2) { // error, input was not in expected format // print error message and exit fprintf(stderr, "Error: invalid input format\n"); return 1; } - students[size].votes = votes; - size++; + + // check if this student already exists + int found = 0; + for (int i = 0; i < size; i++) { + if (strcmp(students[i].name, name) == 0) { + // add votes to existing student + students[i].votes += votes; + found = 1; + break; + } + } + + // if the student was not found, add a new student + if (!found) { + strcpy(students[size].name, name); + students[size].votes = votes; + size++; + } } // sort students based on their votes @@ -60,7 +77,6 @@ int main() { for (int i = 0; i < size; i++) { printf("%d %s\n", students[i].votes, students[i].name); } - // printf("\n"); return 0; }