-1

I'm a Java programmer trying to learn C for a class and man, I can't wrap my head around this. There's no reason why this shouldn't work and yet it doesn't. I'm trying to write a simple calculator app, and no matter how I write it, the first number I input (variable a) ends up being 0, but the 2nd one is fine. With 5 + 6 as input, the output is 6. What am I missing?

#include <stdio.h>

int main()
{
    long int a, b, c;

    char op;

    c = 0;

    printf("Enter the expression: ");
    scanf("%ld %s %ld", &a, &op, &b);

    switch(op){
        case('+'): c = a+b; break;
        case('-'): c = a-b; break;
        case('*'): c = a*b; break;
        case('/'): c = a/b; break;

        default: break;
    }

    printf("\n%ld", c);

    return 0;

}
jww
  • 97,681
  • 90
  • 411
  • 885
Nihilish
  • 5
  • 4

2 Answers2

1

The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.

So always check if scanf is successful and if the number of items are correctly assigned.

And it is good to know about the conversion specifiers (what follows after % character) and the length modifiers and their meanings in C.

Check out C Committee Draft (N1570) sections 7.21.6.2 The fscanf function and 7.21.6.4 The scanf function and you will get a good idea of how to use scanf.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
P.W
  • 26,289
  • 6
  • 39
  • 76
0

I am not sure if you are giving 5<space>+<space>6 or 5+6(without spaces) as input. If you are doing the first, then try doing the second one, i.e, number1+number2 without spaces between the characters. And remove the spaces in the scanf("%ld %s %ld") too.

Hope this helps.

Harshith Rai
  • 3,018
  • 7
  • 22
  • 35
  • Indeed, removing the spaces in the input and the scanf declaration did the trick. But why? – Nihilish Sep 07 '18 at 15:31
  • I think this link might be helpful @Nihilish. https://stackoverflow.com/questions/47903523/white-space-in-format-string-of-scanf – Harshith Rai Sep 10 '18 at 05:31