homework-00: Use getline and strtol instead to account for special cases

This commit is contained in:
Tomáš Kléger 2025-10-05 21:45:06 +02:00
parent 26efaaab55
commit 9e3d232a4f

View File

@ -1,11 +1,14 @@
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
const char * PROMPT = "ml' nob:";
const char * INPUT_OKAY = "Qapla'";
const char * OUT_OF_RANGE = "Qih mi'";
const char * NOT_A_NUMBER = "Neh mi'";
const char * INVALID_NUMBER = "bIjatlh 'e' yImev";
const char * QUOTES[9] = {
"noH QapmeH wo' Qaw'lu'chugh yay chavbe'lu' 'ej wo' choqmeH may' DoHlu'chugh lujbe'lu'.",
@ -20,18 +23,29 @@ const char * QUOTES[9] = {
};
int main() {
int input = 0;
char *buf = NULL;
size_t len = 0;
char* end;
printf("%s\n", PROMPT);
int result = scanf("%d", &input);
if(result != 1) {
ssize_t chars_read = getline(&buf, &len, stdin);
errno = 0;
long input = strtol(buf, &end, 10);
if(errno == ERANGE || chars_read == -1 || end == &buf[0]) {
printf("%s\n", NOT_A_NUMBER);
return EXIT_FAILURE;
}
if(*end != '\n') {
printf("%s\n", INVALID_NUMBER);
return EXIT_FAILURE;
}
if(input < 0 || input > 8) {
printf("%s %d\n", OUT_OF_RANGE, input);
printf("%s %ld\n", OUT_OF_RANGE, input);
return EXIT_FAILURE;
}