diff --git a/cv5/program.c b/cv5/program.c index 82a6f55..125acae 100644 --- a/cv5/program.c +++ b/cv5/program.c @@ -1,6 +1,7 @@ #include #include #include +#include // Include ctype.h for isdigit function #define SIZE 100 @@ -19,7 +20,7 @@ int compare(const void *a, const void *b) { } else if (student_a->votes < student_b->votes) { return 1; } else { - // if the votes are the same, compare names + // if votes are the same, compare names return strcmp(student_a->name, student_b->name); } } @@ -27,6 +28,7 @@ int compare(const void *a, const void *b) { int main() { struct student students[SIZE]; int size = 0; + int error = 0; // Flag to track if an error occurred // read student data from standard input while (1) { @@ -36,25 +38,25 @@ int main() { // check if the line is empty or just contains newline character 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; } - // 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 int votes; 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; + + // Use sscanf to parse the input line + if (sscanf(line, "%d %[^\n]", &votes, name) != 2 || !isdigit(votes)) { + // If sscanf fails to parse the input correctly or votes is not a number + // Set error flag and continue to the next line + error = 1; + continue; } // check if this student already exists