Character input error in my C program?

I am new to C programming, I made a simple calculator program in C.
The program works, but does not work, it works until the value b is entered after it receives a symbol input and asks for input. I do not know why this is happening, but are there any problems?

here is my code:

 #include <stdio.h> int main() { float a,b; char op; printf("enter a: "); scanf("%f",&a); printf("enter b: "); scanf("%f",&b); printf("enter operation: "); scanf("%c",&op); switch(op) { case '+': printf("\n%.2f %c %.2f = %.2f",a,op,b,a+b); break; case '-': printf("\n%.2f %c %.2f = %.2f",a,op,b,ab); break; case '*': printf("\n%.2f %c %.2f = %.2f",a,op,b,a*b); break; case '/': printf("\n%.2f %c %.2f = %.2f",a,op,b,a/b); break; default: printf("invallid input!!"); } return 0; } 

The program seems to be absolutely correct, but there is still something that I am missing. Answers are welcome.

+5
source share
2 answers

Just put a space before entering the scanf() input character format specifier, and your program will work fine:

 scanf( " %c" , &op ); 
+3
source

When using scanf() it will leave the \n character in the input buffer. The next scanf() save this new line and save it. You need to either add a space in scanf() :

 scanf(" %c", &op); /* to skip any number of white space characters */ 

Or use the getchar() character instead of the character. The getchar() function returns int and EOF on error. It can be used as follows:

 int op = getchar() 

Saves the character found in op . You can also add getchar() after calls to scanf() , which will consume the remaining \n character.

Note: Good practice is to check the result of scanf() . Instead, you should write:

 if (scanf(" %c", &op) != 1) { /* oops, non character found. Handle error */ 
+2
source

Source: https://habr.com/ru/post/1264205/


All Articles