Initialization

This commit is contained in:
Kozar 2024-03-21 17:18:00 +01:00
parent fcac30a233
commit c1417f0744

View File

@ -1,6 +1,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <ctype.h> // Include ctype.h for isdigit function
#define SIZE 100 #define SIZE 100
@ -19,7 +20,7 @@ int compare(const void *a, const void *b) {
} else if (student_a->votes < student_b->votes) { } else if (student_a->votes < student_b->votes) {
return 1; return 1;
} else { } else {
// if the votes are the same, compare names // if votes are the same, compare names
return strcmp(student_a->name, student_b->name); return strcmp(student_a->name, student_b->name);
} }
} }
@ -27,6 +28,7 @@ int compare(const void *a, const void *b) {
int main() { int main() {
struct student students[SIZE]; struct student students[SIZE];
int size = 0; int size = 0;
int error = 0; // Flag to track if an error occurred
// read student data from standard input // read student data from standard input
while (1) { while (1) {
@ -36,25 +38,25 @@ int main() {
// check if the line is empty or just contains newline character // check if the line is empty or just contains newline character
if (r == NULL || (r[0] == '\n' && strlen(r) == 1)) { if (r == NULL || (r[0] == '\n' && strlen(r) == 1)) {
// end of input // end of input or empty line
if (size == 0 && !error) {
// If no valid input was processed and no error occurred, print error message and exit
fprintf(stderr, "Error: No valid input\n");
return 1;
}
break; break;
} }
// check if the line was truncated
if (strlen(line) == SIZE - 1 && line[SIZE - 2] != '\n') {
// line was truncated, handle the error
fprintf(stderr, "Error: input line is too long\n");
return 1;
}
// 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;
char name[SIZE]; char name[SIZE];
if (sscanf(line, "%d %[^\n]", &votes, name) != 2) {
// error, input was not in expected format // Use sscanf to parse the input line
// print error message and exit if (sscanf(line, "%d %[^\n]", &votes, name) != 2 || !isdigit(votes)) {
fprintf(stderr, "Error: invalid input format\n"); // If sscanf fails to parse the input correctly or votes is not a number
return 1; // Set error flag and continue to the next line
error = 1;
continue;
} }
// check if this student already exists // check if this student already exists