Initialization

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

View File

@ -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;
}