Skip to content

Instantly share code, notes, and snippets.

@sant123
Created June 17, 2020 02:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save sant123/fef9916d6d3bb230010efde3033c8e7a to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *read_stdin(void)
{
size_t cap = 4096, /* Initial capacity for the char buffer */
len = 0; /* Current offset of the buffer */
char *buffer = malloc(cap * sizeof(char));
int c;
/* Read char by char, breaking if we reach EOF or a newline */
while ((c = fgetc(stdin)) != '\n' && !feof(stdin))
{
buffer[len] = c;
/* When cap == len, we need to resize the buffer
* so that we don't overwrite any bytes
*/
if (++len == cap)
{
/* Make the output buffer twice its current size */
buffer = realloc(buffer, (cap *= 2) * sizeof(char));
}
}
/* If EOF, clear stdin error for future readings */
if (c == EOF)
{
clearerr(stdin);
}
/* Trim off any unused bytes from the buffer */
buffer = realloc(buffer, (len + 1) * sizeof(char));
/* Pad the last byte so we don't overread the buffer in the future */
buffer[len] = '\0';
return buffer;
}
static char *read_stdin_str(const char *message) {
printf("%s", message);
return read_stdin();
}
int read_stdin_int(const char *message, const char *invalid_message)
{
int n;
printf("%s", message);
char *input = read_stdin();
while (sscanf(input, "%d", &n) != 1)
{
printf("%s", invalid_message);
printf("%s", message);
free(input);
input = read_stdin();
}
free(input);
return n;
}
float read_stdin_float(const char *message, const char *invalid_message)
{
float n;
printf("%s", message);
char *input = read_stdin();
while (sscanf(input, "%f", &n) != 1)
{
printf("%s", invalid_message);
printf("%s", message);
free(input);
input = read_stdin();
}
free(input);
return n;
}
double read_stdin_double(const char *message, const char *invalid_message)
{
double n;
printf("%s", message);
char *input = read_stdin();
while (sscanf(input, "%lf", &n) != 1)
{
printf("%s", invalid_message);
printf("%s", message);
free(input);
input = read_stdin();
}
free(input);
return n;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment