Home > Software design >  Unable to read the char input in C using %c
Unable to read the char input in C using %c

Time:11-07

#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

CodePudding user response:

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);

CodePudding user response:

Prepend the conversion specifier in the format string with a space like

scanf( " %c", &op );
       ^^^^^  

In this case white space characters in the input stream as the new line character '\n' that corresponds to the pressed key Enter will be skipped

CodePudding user response:

The problem is not with scanf but stdin. stdin and stdout refer to the same file in the memory for console application. So there is "\n" in the stdin which you have entered for first scanf which is taken by scanf and stored in op. Try putting scanf("%c", &op); above scanf("%d", &num1); or write fflush(stdin) above scanf("%c", &op);

CodePudding user response:

Try using 'getc' and 'gets' instead. 'scanf' is considered to be unsafe altogether and it would be wise to search for safer alternatives. That way you will have greater control over user input.

  • Related