Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear buffer in receiving multiple strings?

Tags:

c

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;
}
like image 481
dushyantashu Avatar asked Jul 13 '13 09:07

dushyantashu


1 Answers

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;
}
like image 145
Nithin Bhaskar Avatar answered Oct 17 '22 08:10

Nithin Bhaskar