Search code examples
ccharscanfconversion-specifier

Unable to read the char input in C using %c


#include <stdio.h>
#include <stdlib.h>

int main()
{

    int num1;
    int num2;
    char op;

    printf("Enter the first number: ");
    scanf("%d", &num1);
    printf("Enter an operator: ");
    scanf("%c", &op);
    printf("Enter the second number: ");
    scanf("%d", &num2);

    switch(op){

        case'+':
            printf("%d", num1+num2);
            break;

        case'-':
            printf("%d", num1-num2);
            break;

        case'/':
            printf("%d", num1/num2);
            break;

        case'*':
            printf("%d", num1*num2);
            break;

        default:
            printf("Enter a valid Operator");

    }

    return 0;
}

I tried to build a basic calculator with user input. but I am getting an error in this line scanf("%c", &op); I searched in here(Stackoverflow) and I also found the answer that if I put a space in scanf(" %c", &op) then my program will work fine; now the question I have is, Could someone explain me this in laymen's terms for a beginner? Please. Your answer will be much appreciated


Solution

  • scanf manual:

    specifier c:

    Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating null byte is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.

    ie format scanf(" %c", &op).

    After typing the first number for int num1 you type an enter '\n' the next scan for character captures the new line and prints it . So as per the manual, To skip white space first, use an explicit space in the format:

    printf("Enter an operator: ");
    scanf(" %c", &op);
    

    or use like this below:

    printf("Enter an operator: ");
    scanf("%c", &op);
    scanf("%c", &op);