Can anyone help me with this C++ program?

Can anyone help me figure out this Program Design assignment?

  • This is the program description. Write a program that evaluates an expression: Enter an expression: 1+2.5*3 Value of expression: 10.5 The operands in the expression are floating-point numbers; the operators are +, -, *, and /. The expression is evaluated from left to right (no operator takes precedence over any other operator). Specifications: a) You can assume that the expression has the format: an operand followed by an operator, then by an operand, an operator, …, ended with an operand. b) Use float type for the operands and the value of expressions. c) If there is a dividing by zero in the expression, display “Cannot divide by zero” error message and abort the program. d) Skip blank characters in an expression. I want to know if there is a proper way to loop it. It only works properly after I enter 0. I am not supposed to, but this is the only way I could properly get it to work. If anyone has any solutions, please share them. Thank you. #include <stdio.h> int main(void) { char ch; float n, value = 0; printf("Enter an expression: "); scanf("%f%c%f", &value, &ch, &n); while (n != 0) { if (ch == '+') { value += n; } if (ch == '-') { value -= n; } if (ch == '*') { value *= n; } if (ch == '/') { value /= n; } scanf("%c%f", &ch, &n); printf("The value of expression is: %.1f\n", value); } return 0; }

  • Answer:

    What would happen if you ended your input string with an "\n" as in "%f%c%f\n" which would cause the scanf function to wait for an enter and presumably move on with the enter. An alternative would be to do an fgets(STDIN, num, *buffer) -- if you do a gets(buffer) then will or should get a warning that gets is unstable and should not be used -- then split up buffer using sscanf() which works like scanf() except the input is always a string.

Lakers88 at Yahoo! Answers Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.