How do I use a sentinel to calculate the running sum of an expression?

  accumulator, c++, sentinel, while-loop

In this case, the program takes two inputs; numbers and operators and keeps going until the user enters "=" which is the sentinel and marks the end of the expression after which, the program should return the total value of the expression.

So far, I’ve got this far but I am stuck now and just can’t seem to make it work. Can someone please tell me what am I missing?

// this program finds the value of the expression-
// defined by the sequence of operands and operators
// enters a series of numbers and + or - then,
// " = " when finished

#include <cstdlib>
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    float total = 0, num; // Accumulator
    string operand;

    cout << "Enter a number:n ";
    cin >> num; // could be positive or negative
    cout << "Enter an operand:n "; // either "+" or "-" only
    cin >> operand;

    while (operand != "=") // "=" being the sentinel
    {
        if (operand == "+")
        {
            total = total + num;
        }

        if (operand == "-")
        {
            total = total - num;
        }
        cin >> num;
        cin >> operand;
    }

    cout << "nThe total value of the expression is "<< total << endl;
    return 0;
}

Source: Windows Questions C++

LEAVE A COMMENT