Code does not handle bad input well.
In two places scanf("%f %c\n", &num, &op)
has trouble with if non-numeric input is entered. The scanf()
fails, so num
and op
retain their old values. The operation based on op
occurs again and the next scanf()
tries again with the same data.
The "%f %c\n"
in 2 places is misleading in that the \n
performs differently than OP expectations. Change to
scanf("%f %c", &num, &op);
Instead of using scanf()
, recommend using
char buf[100];
if (fgets(buf, sizeof(buf), stdin) == NULL) {
exit(-1); // handle EOF or error
}
if (sscanf(buf, "%f %c", &num, &op) != 2) {
exit(-1); // syntax error.
}
Alternatively one could use the following. Bad input will eventually get consumed but not so readily.
if (2 != scanf(" %c %f", &op, &num)) {
; // syntax error.
}
Other issues: accumulator is not initialized
float accumulator = 0.0;