Initialization

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

View File

@ -1,7 +1,6 @@
#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
@ -28,7 +27,6 @@ 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,27 +34,19 @@ int main() {
memset(line, 0, SIZE); memset(line, 0, SIZE);
char *r = fgets(line, SIZE, stdin); char *r = fgets(line, SIZE, stdin);
// check if the line is empty or just contains newline character // check if the line is empty
if (r == NULL || (r[0] == '\n' && strlen(r) == 1)) { if (r == NULL || (r[0] == '\n' && strlen(r) == 1)) {
// end of input or empty line // end of input
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;
} }
// 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) {
// Use sscanf to parse the input line // error, input was not in expected format
if (sscanf(line, "%d %[^\n]", &votes, name) != 2 || !isdigit(votes)) { // print error message and exit
// If sscanf fails to parse the input correctly or votes is not a number break;
// Set error flag and continue to the next line
error = 1;
continue;
} }
// check if this student already exists // check if this student already exists