I need to collect user input with only getchar() and malloc() to store it in a string (of which the size is unknown). I've done it before but forgot how I got it right and now I'm having a problem with the string, only printing the first letter which means my get_string function is not collecting all the chars from the stdin OR the pointer is not pointing to it OR it's just not printing correctly with printf.
char *get_string(void);
int main(void)
{
printf("Input string: ");
char *p = get_string();
printf("Output string: %s\n", p);
}
char *get_string(void)
{
int c = 0;
char *str = NULL;
char *buff = NULL;
for(int i = 0; c != '\n'; i++)
{
if(i > 0) // skips on first iteration (no char collected yet)
{
if(i > 1) // skips on second iteration (1st char collected)
{
buff = malloc(i + 1);
for(int j = 0; j < i - 1; j++)
buff[j] = str[j];
free(str);
}
str = malloc(i + 1); // allocate space for string
if(i > 1) // no need to copy string from buffer
{
for(int j = 0; j < i - 1; j++)
str[j] = buff[j];
free(buff);
}
str[i - 1] = c; // place char into string
str[i] = '\0'; // terminate string with '\0'
printf("%s\n", str); // print contents on each iteration
}
c = getchar();
}
return (str);
}
If I run printf in the main with the returned string, nothing is printed. If I run the printf inside the loop it only prints on the first iteration (first letter).
What I get:
$ > gcc get_string.c -o get_string
$ > ./get_string
Input string: Hello World!
H
Output string:
What I expect:
$ > gcc get_string.c -o get_string
$ > ./get_string
Input string: Hello World!
H
He
Hel
Hell
Hello
...
Output string: Hello World!
Also, if you know a better (and shorter) way to approach this, please share.
strcpyrealloc; your data will be fragmented, but it might be easier.