homework-00: Use getline and strtol instead to account for special cases
This commit is contained in:
parent
26efaaab55
commit
9e3d232a4f
@ -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;
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user