Skip to content

Instantly share code, notes, and snippets.

@wisentini
Created April 8, 2021 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wisentini/d46f290cad85109c2a1e7fc2b7289628 to your computer and use it in GitHub Desktop.
Save wisentini/d46f290cad85109c2a1e7fc2b7289628 to your computer and use it in GitHub Desktop.
A function to read a string of unknown length from stdin in C.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
char *get_str(void)
{
char *str = malloc(sizeof (char));
if (!str) {
printf("\nUnable to allocate memory.\n");
exit(EXIT_FAILURE);
}
size_t index = 0;
size_t length = 1;
while (true) {
int temp_char = getc(stdin);
if ((temp_char == '\n') || (temp_char == EOF)) {
str[index] = '\0';
return str;
}
str[index] = (char)temp_char;
index++;
length++;
char *temp_str = realloc(str, length * sizeof (char));
if (!temp_str) {
printf("\nUnable to reallocate memory.\n");
exit(EXIT_FAILURE);
}
str = temp_str;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment