The built in functions like scanf
will do it but the problem I have with them is that you need to know ahead of time how much input you will receive. What if it's 1 character? What if it's 10000? So I prefer to dynamically allocate memory using malloc
and realloc
and build the string as the input is received. This is what I use when I need to read from stdin
or a file. It is simple enough, probably far from perfect, it simply gets a character from stream and if it isn't the newline or EOF
it adds it to the string. If the reallocation fails it frees the entire string as I need to have an "all or nothing" approach to building the string. It returns a pointer to the string or NULL
or any failure.
char* get_str(FILE* stream)
{
char *s;
int ix = 0, sz = 1, rf = 0, ch;
if(stream == NULL) {
s = NULL;
} else {
s = (char*)malloc(sizeof(char) * sz);
if(s != NULL) {
s[ix] = '\0';
ch = fgetc(stream);
while(ch != '\n' && ch != EOF && rf == 0) {
sz++;
s = (char*)realloc(s, sizeof(char) * sz);
if(s != NULL) {
s[ix] = ch;
ix++;
s[ix] = '\0';
ch = fgetc(stream);
} else {
rf = 1;
free(s);
s = NULL;
}
}
}
}
return s;
}
And then you call it like this:
int main()
{
char *s = get_str(stdin); /* or a file you opened with fopen, etc */
printf("%s\n", s);
free(s);
return 0;
}
Just remember that memory allocated with either malloc
, calloc
, or realloc
needs to be freed.