Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top