0

When I run this code this is my output:

$ make 6-4 && ./6-4
`6-4' is up to date.
Begin calculations
S 3
 = 3.000000
+ 2
Invalid operator
 = 3.000000
 = 5.000000

It starts off well, 'S 3' gives me ' = 3.000000'. Than I type "+ 2", this gives me 'Invalid operator' and two answers. This is what I want:

S 3
 = 3.000000
+ 2
 = 5.000000

What am I missing?

#include<stdio.h>

char operator;
float number = 0;
float result = 0;

main()
{
        printf("Begin calculations\n");

        while (1) {
                scanf("%c%f", &operator, &number);
                switch(operator)
                {
                        case '+': {
                                result += number;
                                break;
                                }
                        case '-': {
                                result -= number;
                                break;
                                }
                        case '*': {
                                result *= number;
                                break;
                                }
                        case '/': {
                                result /= number;
                                break;
                                }
                        case 'S': {
                                result = number;
                                break;
                                }
                        case 'E': {
                                return 0;
                                break;
                                }
                        default: {
                                printf("Invalid operator\n");
                                break;
                                }
                }
                printf(" = %f\n", result);
        }
}

Thanks.

3 Answers3

3

In your case your scanf reads newline character into &operator in the second invocation. To skip blank characters, try to use:

scanf(" %c%f", &operator, &number);

instead. I.e. put one space character at the beginning of your format. It may be a good idea to put one space also between %c and %f.

Marian
  • 7,402
  • 2
  • 22
  • 34
0

When reading the second line of input, the scanf() is reading the \n newline character for the %c format spec.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
0

Try to print the value of operator and number so that we will have an idea why the value is not executing case '+' instead.

user3462803
  • 170
  • 1
  • 2
  • 10
  • @chouaib: I'm trying to help but I can't add a comment. Sorry for this. Should I remove it? – user3462803 Apr 21 '14 at 08:19
  • I thought it should be better used as a comment also. Sorry didn't know you can't comment. No just leave it in this case. – chouaib Apr 21 '14 at 08:21