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?