4

I really don't know what's the mistake. It seems to be right, doesn't it?

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

int main(int argc, char *argv[])
{
   char op;

   printf("Type in operator (+,-,/,*):");
   scanf("%i",&op);

   if(op == '+')
   {
      printf("You entered a plus");
   }

   system("pause"); 
   return 0;
}

I expected it to print "You entered a plus" when entering a +. It does not.

I'm kinda new to C. Thanks in advance :)

phil.seven
  • 43
  • 3
  • 1
    Since you're new to C, please try to avoid picking up bad habits - like calling [`system("pause")`](http://stackoverflow.com/questions/1107705/systempause-why-is-it-wrong). – Nik Bougalis Apr 06 '13 at 15:16
  • Also, enable all warnings and debugging info in your compiler (e.g. use `gcc -Wall -g` on Linux), improve the code till no warnings are given, and learn how to use the debugger. – Basile Starynkevitch Apr 06 '13 at 15:58

3 Answers3

4

The if condition is fine. The problem is the scanf() format, which should be

scanf("%c",&op);

(%i reads an integer whereas %c reads a char.)

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • thank you for the very fast answer, it works now :) but another issue: when i want the user to enter an integer before entering the char, the console jumps over it and doesn't give him even a try to enter... like: printf("Enter number:"); scanf("%i",&number); printf("Enter char:"); scanf("%c",&op); – phil.seven Apr 06 '13 at 15:17
  • what's the matter with that? I'm trying to make a calculator. After entering the last Integer-number it overjumps the query for entering an operator (as char). ?? – phil.seven Apr 06 '13 at 15:31
  • 1
    The new line character `'\n'` from when you pressed ENTER after typing the integer is still there and the `scanf` reads that instead of the operator. Think about how you can use a loop to skip newline characters. – Nik Bougalis Apr 06 '13 at 15:35
  • You may want to learn about `getc` and `getchar` ... Also remember that `stdin` (and also `stdout`) are often "line buffered" – Basile Starynkevitch Apr 06 '13 at 15:57
0
scanf("%i", &op);

You are expecting an integer. So, when you write a character and press <Enter>, scanf fails (you can check its return value to see it):

if (scanf("%i", &op) != 1)
{
    /* Treat the error. */
}

Use rather %c format in scanf to read characters:

scanf("%c", &op);
md5
  • 23,373
  • 3
  • 44
  • 93
0

Your problem is with wrong format specifier

//In scanf instead of 
scanf("%i",&op);
// you have to provide 
scanf("%c",&op);

%i use for reading integer whereas %c use for reading char.
Gevni
  • 43
  • 2
  • 10