Search code examples
cwhile-loopruntime-errorascii

Found error while printing the ascii value of a character


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:


Solution

  • 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.