Created
April 8, 2021 21:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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