Last active
September 15, 2019 15:09
-
-
Save flux77/9892a7dfb930935168059abe624aeae7 to your computer and use it in GitHub Desktop.
Read string of any length in C https://codereview.stackexchange.com/questions/228979/read-string-of-any-length-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
/* Improved version for https://codereview.stackexchange.com/questions/228979/read-string-of-any-length-in-c */ | |
#include <stdlib.h> | |
#include <stdio.h> | |
/* Reads string input up to, but not including, the first newline or EOF. | |
* Returns a pointer to the string, or NULL on error. | |
* The pointer to the string must be freed. | |
*/ | |
char* input() { | |
size_t bufsize = 10; /* Initial buffer size. */ | |
char *s = malloc(bufsize); | |
if (s == NULL) { | |
return NULL; | |
} | |
size_t s_len = 0; /* Current length of string excluding null character. */ | |
int ch; | |
while((ch = getchar()) != '\n' && ch != EOF) { | |
s[s_len] = (char) ch; | |
s_len++; | |
if (s_len + 1 > bufsize) { | |
bufsize *= 2; | |
char *temp_buf = realloc(s, bufsize); | |
if (temp_buf == NULL) { | |
free(s); | |
return NULL; | |
} | |
s = temp_buf; | |
} | |
} | |
s[s_len] = '\0'; | |
return s; | |
} | |
int main() { | |
printf("Name: "); | |
fflush(stdout); | |
char *s = input(); | |
if (s == NULL) { | |
fprintf(stderr, "Error: input()\n"); | |
exit(1); | |
} | |
printf("%s\n", s); | |
free(s); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment