+ 1

How can I use the "if" function with a "char" value in C?

I would like to do a calculator using a char caracter instead of an integer in an if function. Something like this: #include<stdio.h> int main(){ int a,b; printf("put the numbers you want to sum"); scanf("%d",&a); scanf("%d",&b); char c; printf("chose an operator"); scanf("%c",&c); if (c=="+") printf("%d",a+b); if (c=="-") printf(....) and so on. The problem is that it doesn't work and i dont't know how to sort this out. Any suggestion? (i already know that i could do something like if (num==1) printf(...) but i wanted to use a char)

2nd Oct 2018, 5:10 PM
Anagoor Avangor
Anagoor Avangor - avatar
3 odpowiedzi
+ 3
A character is typically enclosed in single quotation marks, i.e. these: ' '. So try using c == '+' instead for comparison.
2nd Oct 2018, 5:28 PM
Shadow
Shadow - avatar
+ 1
I've tried but it doesn't work, it tells me that i've done no mistakes but it doesn't run the if operation
3rd Oct 2018, 5:08 PM
Anagoor Avangor
Anagoor Avangor - avatar
+ 1
In that case, you probably entered the input like this: 1 1 + Just for example. Well, the problem is the enter after the second number, which is also a character! So c reads in the enter instead of the '+'. Here you can find a description of the problem aswell as a working solution: https://gsamaras.wordpress.com/code/caution-when-reading-char-with-scanf-c/
4th Oct 2018, 10:21 AM
Shadow
Shadow - avatar