0

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;
}
Daksh
  • 27
  • 5
  • 1
    In the future, always present a [mre] for debugging problems, including an exact copy of text that reproduces the problem, an exact copy of the observed output of the program, and a sample of the output desired instead. – Eric Postpischil Nov 05 '22 at 17:36
  • I don't recommend that you use `scanf` for reading user input. Rather, I suggest that you always read a whole line of input at once from the user using the function [`fgets`](https://en.cppreference.com/w/c/io/fgets), instead of attempting to read individual characters. That way, issues such as the one you are having will be gone. You may want to read this: [What can I use for input conversion instead of scanf?](https://stackoverflow.com/q/58403537/12149471) – Andreas Wenzel Nov 05 '22 at 17:53

1 Answers1

2

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.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312