0

I wrote a simple program to make basic operation in prefix notation (operator operand1 operand2):

#include <stdio.h>
#include <stdlib.h>

#define MAX 5
float operando(char s[], float precedente);
float operazione(float o1, float o2, char operatore);

int main(void)
{
    char operatore;
    char operando1[MAX], operando2[MAX];
    float precedente = 0;
    float o1, o2;

    printf("Scrivi l'operazione con questo formato: operatore operando1 operando2;\nPREV al posto di uno dei due operandi per usare l'ultimo risultato.\nLettera qualunque per terminare\n");   
    do 
    {
        scanf("%c %s %s", &operatore, operando1, operando2);
        o1 = operando(operando1, precedente);
        o2 = operando(operando2, precedente);
        precedente = operazione(o1, o2, operatore);
        printf("%c %f %f = %f\n\n", operatore, o1, o2, precedente);
        scanf("%*c");
    } while(operatore == '+' || operatore == '-' || operatore == '*' || operatore == '/');

    return 0;
}

float operando(char s[], float precedente)
{
    if (strcmp(s, "PREV") == 0)
        return precedente;
    else
        return atof(s);
}

float operazione(float o1, float o2, char operatore)
{
    switch (operatore)
    {
    case '+':
        return o1 + o2;
        break;
    case '-':
        return o1 - o2;
        break;
    case '*':
        return o1*o2;
        break;
    case '/':
        return o1 / o2;
        break;
    }
}

If I run this program, it works only the first time, then it takes '\n' as character and put it in operator variable. So I add after the last printf a simple line: scanf("%*c");

With this line the program works correctly. I don't understand: why without discarding '\n' it doesn't use the last character read? How can I know, before running a program, when to discard a character?

Simone
  • 3
  • 2
  • 1
    perhaps reading this post will help: http://stackoverflow.com/questions/13542055/how-to-do-scanf-for-single-char-in-c – bruceg Oct 07 '16 at 17:19
  • `scanf()` is a beast. Use fgets() and do the parsing yourself. – alk Oct 07 '16 at 17:20

1 Answers1

1

The %c format specifier to scanf will ready any character, including whitespace characters like spaces or newlines. You need to add a space before the %c which will absorb any whitespace characters:

scanf(" %c %s %s", &operatore, operando1, operando2);
dbush
  • 205,898
  • 23
  • 218
  • 273