From 49a5b684555dcd0bd101d546dc843e5f4f815e5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Thu, 21 Jan 2021 11:43:35 +0100 Subject: add read helpers --- main.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/main.c b/main.c index 05f17ac..abe0ef6 100644 --- a/main.c +++ b/main.c @@ -8,6 +8,32 @@ struct student { struct list_elem elem; }; +// Read a line from stdin, strip the eventual newline and return a pointer +// to the string. Remember to free the pointer. +char *read_input() { + char *buf = NULL; + size_t buf_size = 0; + size_t read = getline(&buf, &buf_size, stdin); + if (read == -1) { + free(buf); + buf = NULL; + } else if (read >= 1 && buf[read - 1] == '\n') { + buf[read - 1] = '\0'; + } + return buf; +} + +int read_int() { + char *buf = read_input(); + int res = -1; + if (!buf) { + printf("Failed to read int from stdin\n"); + } else { + res = atoi(buf); + } + free(buf); + return res; +} void insert (struct list *student_list) { } -- cgit v1.2.1