Search code examples
cscanf

why is the c function not scanning 2nd time using scanf function?


I am stuck in this program, help me, it'll be appreciatable. But, scanning the characters together might work. I want to know why is scanf not asking for the character in 2nd time.

#include <stdio.h>

int main()
{
    printf("--Mathematical operations on character to get other character--\n");

    char a, b;

    printf("Enter the 1st character: \n");
    scanf("%c", &a);

    printf("Enter the 2nd character: \n");
    scanf("%c", &b);//It's not scanning 2nd time, instead moving forward to printf function

    printf("\nThe ASCII equivalent for addition of %c and %c is %c\n", a, b, (a + b));
    printf("\nThe ASCII equivalent for subtraction of %c and %c is %c\n", a, b, (a - b));
    printf("\nThe ASCII equivalent for multiplication of %c and %c is %c\n", a, b, (a * b));
    printf("\nThe ASCII equivalent for division of %c and %c is %c\n", a, b, (a / b));
    printf("\nThe ASCII equivalent for modular division of %c and %c is %c\n", a, b, (a % b));

    return 0;
}

Solution

  • After scanf("%c", &a);, the next character in the input stream is the \n from the user pressing return or enter. Then scanf("%c", &b); reads that character.

    To tell scanf to skip the \n, use scanf(" %c", &b);. The space tells scanf to read all white-space characters until a non-white-space character is seen.