Initialization
This commit is contained in:
parent
fcac30a233
commit
c1417f0744
@ -1,6 +1,7 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ctype.h> // 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
|
||||
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");
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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
|
||||
|
Loading…
Reference in New Issue
Block a user