Search code examples
cscanfstdinflush

Flushing stdin after inputing a string, to subsequently input next char


I want to input a string, the subsequently a char for further use in my program, but whenever I try to input a string longer than 10 characters, all that's leftover, goes into my next input request. I tried using scanf("%*c"), but it couldn't flush all my input.

char tab[11];
char c;
printf("Give me a string: ");
scanf("%10[^\n]%*c", tab);
printf("%s\n", tab);
printf("Give ma a char: ");
scanf("%c", &c);

How should I properly deal with this issue?


Solution

  • Run getchar in a loop until you read a newline:

    printf("Give me a string: ");
    scanf("%10[^\n]", tab);
    
    while (getchar() != '\n');
    
    printf("%s\n", tab);
    printf("Give me a char: ");
    scanf("%c", &c);