0

Hi everyone i made a little program in C referred to a book exercise. It's purpose is to do some simple math operations asking the user for the math operator and a number and using them with an accumulator. This is the code:

/* Printer program, take a number and various operators */

#include <stdio.h>

int main(void)
{
    char var;
    _Bool end = 0;
    float value, accum;
    accum = 0.0;


    printf("Welcome to the printer, please select your operation
    writing the right character\n");
    printf("1. + For addiction\n");
    printf("2. - For subtraction\n");
    printf("3. * For moltiplication\n");
    printf("4. / For division\n");
    printf("5. S To accumulate a number\n");
    printf("6. E To end the program\n");

    while( end == 0)
    {
        printf("Enter the sign and the value: ");
        scanf("%c %f", &var, &value);

        switch(var)
        {
            case '+':
            printf("Add by %.2f = %.2f\n", value, accum + value);
            accum += value;
            break;

            case '-':
            printf("Subtract by %.2f = %.2f\n", value, accum - value);
            accum -= value;
            break;

            case '*':
            printf("Multiply by %.2f = %.2f\n", value, accum * value);
            accum *= value;
            break;

            case '/':
            printf("Divide by %.2f = %.2f\n", value, accum / value);
            accum /= value;
            break;

            case 'S':
            printf("Set accumulator to %.2f\n", value);
            accum = value;
            break;

            case 'E':
            printf("Goodbye!\n");
            end = 1;
            break;

            default:
            printf("No valid character, retry\n");
            break;

        }


    }

    return 0;
}

Now, the first time the while loop is executed it seems to be all ok, but after the first execution it start getting strange. The program can't identify all the operators and it continue to duplicate displayed printfs. This i a screen i made: https://i.stack.imgur.com/1Lv31.jpg

What could be the problem? I'm pretty new to programming and sorry for my english.

Jockeyxn
  • 1
  • 1
  • 2
    This question has been asked a thousand times now. Put a `space` in front of the `%c` format. `scanf(" %c %f", &var, &value);` This will clean off previous whitespace (such as `newline`) in the input buffer. The `%f` format will clean off leading whitespace, but not the following `newline`. But `%c` takes just what is there. – Weather Vane Sep 10 '16 at 19:48
  • Also might be helpful: http://stackoverflow.com/questions/6582322/what-does-space-in-scanf-mean – l'L'l Sep 10 '16 at 19:54
  • Thank you so much, i will look better for similar questions next time. – Jockeyxn Sep 11 '16 at 08:36

0 Answers0