0

After first successful iteration, the second print statement is automatically getting printed. It is taking a whitespace its input. Why does this happen?

    #include<stdio.h>
    int main() {
        char c;
        while (1)
        {
            printf("\nEnter any character to get its ASCII value - ");
            scanf("%c",&c);
            printf("Ascii value of %c : %d",c,c);
        }
        
    }

Sample output:

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574

1 Answers1

1

It's because the linefeed still remains in the input buffer, change scanf("%c",&c); to scanf(" %c",&c); and it'll work as expected.

  • Yeah, It worked. But will you please explain to me how the linefeed is remaining in the input buffer. Because, I had even tried re-declaring the variable(char c) as null during next iteration. But I was still facing the same issue. – Sushil Dikondwar Jul 04 '21 at 17:53
  • @SushilDikondwar Re-declaring won't work, the linefeed remains in the input buffer not in the variable `c`, so during the next iteration of the while loop, `c` reads from the input buffer which has the linefeed (`\n`) in it. – JASLP doesn't support the IES Jul 05 '21 at 04:18