Initialization

This commit is contained in:
Kozar 2024-03-21 16:51:55 +01:00
parent 863b933c07
commit fa0f26fda1

View File

@ -42,15 +42,32 @@ int main() {
// parse the string and extract number of votes and student name // parse the string and extract number of votes and student name
int votes; 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 // error, input was not in expected format
// print error message and exit // print error message and exit
fprintf(stderr, "Error: invalid input format\n"); fprintf(stderr, "Error: invalid input format\n");
return 1; return 1;
} }
// 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; students[size].votes = votes;
size++; size++;
} }
}
// sort students based on their votes // sort students based on their votes
qsort(students, size, sizeof(struct student), compare); qsort(students, size, sizeof(struct student), compare);
@ -60,7 +77,6 @@ int main() {
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
printf("%d %s\n", students[i].votes, students[i].name); printf("%d %s\n", students[i].votes, students[i].name);
} }
// printf("\n");
return 0; return 0;
} }