Nikhil George Nikhil George - 4 months ago 31
C Question

Clear input buffer after fgets() in C

#include <stdio.h>
int main()
{
char name[10];
for(int i=0;i<=10;i++)
{
printf("Who are you? ");
if(fgets(name,10,stdin)!=NULL)
printf("Glad to meet you, %s.\n",name);
}
return(0);
}


When I input something greater than 10 characters the loop skips.

Who are you? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Glad to meet you, aaaaaaaaa.
Who are you? Glad to meet you, aaaaaaaaa.
Who are you? Glad to meet you, aaaaaaaaa.
Who are you? Glad to meet you, aaaaaaaaa.
Who are you? Glad to meet you, aaaaaaaaa.
Who are you? Glad to meet you, aaaaaaaaa.
Who are you? Glad to meet you, aaaaaaa


I guess I want to clear the input buffer from the remaining characters. What will be the best way to do that...?

Answer

check exist newline in name.

#include <stdio.h>
#include <string.h>

int main(void){
    char name[10];

    for(int i=0;i<=10;i++){
        printf("Who are you? ");
        if(fgets(name,10,stdin)){
            char *p;
            if(p=strchr(name, '\n')){//check exist newline
                *p = 0;
            } else {
                scanf("%*[^\n]");scanf("%*c");//clear upto newline
            }
            printf("Glad to meet you, %s.\n", name);
        }
    }
    return(0);//Parentheses is not necessary
}