If I enter str1
longer than length 10, the rest of it remains in the buffer and gets entered into my str2
. How to clear the buffer before str2
, so I can input it?
#include <stdio.h>
int main(void)
{
char str1[10];
char str2[10];
fgets(str1,10,stdin);
fgets(str2,10,stdin);
puts(str1);
puts(str2);
return 0;
}
After fgets(str1,10,stdin);
do
while((c = getchar()) != '\n' && c != EOF);
This would clear the input buffer after 'str1' is read.
So your code should be
#include <stdio.h>
int main()
{
char str1[10];
char str2[10];
int c;
str1[0]=0;
str2[0]=0;
fgets(str1,10,stdin);
if( (str1[0]!=0) && (!strrchr(str1,'\n')) )
while((c = getchar()) != '\n' && c != EOF);
fgets(str2,10,stdin);
puts(str1);
puts(str2);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With