ayush
ayush

Reputation: 3

char in buffer preventing input of integer

#include <stdio.h>

int main(void) {
    int n,m=5;
    char c;
    while(m>0)
    {
        m--;
        scanf("%d",&n);
        if(n==42)
        break;
        printf("%d",n);
        fflush(stdin);
        scanf("%c",&c);
        puts(&c);       
    }
    return 0;
}

Although I know that when a enter is pressed after entering a number at first scanf, it(enter) is taken as input by the second scanf, but my doubt is that, when I give 5ttttt as input , the output is

5t
5t
5t
5t
5t

as there is no integer in input buffer, why it is not asking for input of integer| Second question is, even if we follow the above behavior, then on giving input of 5t and then pressing enter should take two characters as buffer ('t' and 'enter') but only t is taken in buffer and the output is

5t

but I expected the output

5t
5

as 'enter' would be taken in buffer and it will not ask for integer input in the second iteration of loop.

Upvotes: 0

Views: 216

Answers (2)

Najat
Najat

Reputation: 197

Avoid fflush(stdin). Instead of fflush(stdin) you can use getchar(). After giving an integer input by scanf("%d", &n) you'll press an Enter, right? That \n (new line character) will be taken by getchar() and you can safely take a character input by scanf("%c", &c). Otherwise the \n will be taken by c.

Upvotes: -1

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

First of all, see this thread about fflush(stdin); being undefined behaviour, simply don't do it.

You can roll your own function go get this done. Something along the line of

  while ((c = getchar()) != '\n' && c != EOF) { }

should do the job nicely.

That said,

   puts(&c);  

also causes undefined behavior, as &c does not point to a string. Variable c is of type char, it's not a char array with a mandatory null-termination required to be considered as string. so, due to memory overrun, you're essentially accessing out of bound memory which causes the UB.

Probably you want to use putchar() instead.

Upvotes: 2

Related Questions