Reputation: 33
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
int main(void) {
char a[1001];
int t,i;
scanf("%d",&t);
while(t--)
{
fflush(stdin);
gets(a);
printf("%d\t",t);
puts(a);
}
return 0;
}
Input:
2
die another day.
i'm batman.
Ouput:
1
0 die another day.
Expected Output:
1 die another day.
0 i'm batman.
Anyone please help how to accept more than one string without any bugs. I am able to see after entering 2 my gets is taking newline as first string and later second string properly. Thanks in advance
Upvotes: 0
Views: 6287
Reputation: 400079
Stop using scanf()
of stdin
to read input. Never call fflush(stdin);
either, but if you stop using scanf()
you will no longer want to.
Read whole lines using fgets()
into suitably-sized string buffers, then parse what you got. One good function for parsing a string is sscanf()
which is just like scanf()
except it reads from a string instead.
This will be much easier, less annoying, and just generally better. Oh, and of course never use gets()
.
Something like this (untested):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char line[256];
if(fgets(line, sizeof line, stdin))
{
int count;
if(sscanf(line, "%d", &count) == 1)
{
while(count > 0)
{
if(fgets(line, sizeof line, stdin))
{
printf("%s", line);
--count;
}
else
break;
}
}
}
return EXIT_SUCCESS;
}
Upvotes: 2
Reputation: 3162
Dont use fflush(stdin). use getchar()
to clear the [enter] character left after scanf()
as,
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
int main(void) {
char a[1001];
int t,i;
scanf("%d",&t);
getchar();
while(t--)
{
gets(a);
printf("%d\t",t);
puts(a);
}
return 0;
}
it works.
Upvotes: 0