Reputation: 1928
How to read several strings in a loop, each of whose length is not previously known ? I tried the following but its not working as desired.
int main()
{
int j, i = 0;
char c;
char *buf = malloc(20);
size = 20;
for(j = 0; j < 10; j++)
{
i = 0;
while(1)
{
if(i == size)
{
buf = realloc(buf,size+10);
size += 10;
}
char c = getchar();
if(c == '\n')
break;
buf[i] = c;
i++;
}
buf[i] = '\0';
printf("%s\n", buf);
}
}
It works only if i am taking these strings as inputs. But say i have a scanf("%d",&j) right before i take string inputs then pressing enter for this scanf would make my first string empty
Upvotes: 1
Views: 336
Reputation: 409196
The problem with you using e.g. scanf
before reading your strings in the way you do in the question, is that the scanf
call leaves the newline in the input buffer. So the first character fetched by getchar
is this newline, leading to your first line being empty.
You can solve this in a couple of ways:
Tell scanf
to discard any trailing whitespace by using
scanf("%d ", &i);
Notice the space after the format code.
Manually skip whitespace:
int c;
while ((c = fgetc(stdin)) != EOF && isspace(c))
;
/* `c` is now a non-space character or EOF, put it back if it's not EOF */
if (c != EOF)
ungetc(c, stdin);
Upvotes: 2