1
#include <stdio.h>

int main() {
    int n1,n2 ;

    char operator ;

    printf("enter the expression");

    scanf("%d","%c","%d",&n1,&operator,&n2);

    if (operator == '+') {
        printf("%d+%d=%d",n1,n2,n1+n2);
    } else if (operator == '-') {
        printf("%d-%d=%d",n1,n2,n1-n2);
    } else if (operator == '*') {
       printf("%d*%d=&d",n1,n2,n1*n2);
    } else if (operator == '/') {
        printf("%d/%d=%d",n1,n2,n1/n2);
    } else {
        printf("wrong input");
    }
    return 0;
}

This code shows no error but does not run as expected. After i enter the expression, it does not give me an output

Rudi
  • 17,566
  • 3
  • 50
  • 74
Rohan 1501
  • 21
  • 2
  • 1
    Does this answer your question? [Why does printf not flush after the call unless a newline is in the format string?](https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin) – Peter Dec 23 '20 at 09:37
  • 1
    If you use [GCC](http://gcc.gnu.org/) as your compiler, be sure to compile with `gcc -Wall -Wextra -g`. Read of course [*Modern C*](https://modernc.gforge.inria.fr/), and [this C reference](https://en.cppreference.com/w/c) and the documentation of your compiler. Consider using [GCC](http://gcc.gnu.org/) with [GDB](https://www.gnu.org/software/gdb/), but read their documentation first, and perhaps use [Frama-C](https://frama-c.com/) – Basile Starynkevitch Dec 23 '20 at 11:30
  • BTW [GNU bison](https://www.gnu.org/software/bison/) has many examples, including a calculator – Basile Starynkevitch Dec 23 '20 at 11:35

2 Answers2

1

Your scanf call is incorrect. You should put everything in one string:

scanf("%d%c%d",&n1, &operator, &n2);

See also the documentation.

I tried it and it works now.

Bart Friederichs
  • 30,888
  • 13
  • 85
  • 169
  • 1
    and also add fflush(stdin); after using scanf – larsaars Dec 23 '20 at 10:03
  • 3
    @Lurzapps ... no, not really. the behavior of `fflush(stdin);` is not defined by the [C Standard](http://port70.net/~nsz/c/c11/n1570.html) or [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/). Windows [defines it](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fflush?view=msvc-160), which is ok **for Windows systems**. Once you start thinking about using your code in different Operating Systems you need to replace all `fflush(stdin);` with something else. I suggest you do not use `fflush(stdin);` even on Windows systems and completely avoid future problems. – pmg Dec 23 '20 at 13:00
  • 1
    @Lurzapps no, the safe way is to use fgets to read from the keyboard and sscanf to retrieve the values. – AndersK Dec 23 '20 at 13:17
  • ok, i did not know that – larsaars Dec 23 '20 at 14:49
-1

You can do the scanf separately or you can do a array (this option let's you have more control, but you have to do more things )