Untitled

 avatar
unknown
plain_text
18 days ago
1.6 kB
4
Indexable
#include <iostream>
#include <cctype>
#include <stdexcept>
using namespace std;

int main() {
    string expr;
    cout << "Enter a simple expression (single-digit numbers, +, -, *, / only): ";
    cin >> expr;

    int result = 0;
    char lastOperator = '+';  // Assume the first operator is '+' for the first digit

    // Loop through the expression one character at a time
    for (int i = 0; i < expr.length(); ++i) {
        char ch = expr[i];

        // Check if character is a digit
        if (isdigit(ch)) {
            int num = ch - '0';  // Convert character to integer

            // Perform operation based on the last operator encountered
            if (lastOperator == '+') {
                result += num;
            } else if (lastOperator == '-') {
                result -= num;
            } else if (lastOperator == '*') {
                result *= num;
            } else if (lastOperator == '/') {
                // Handle division by zero
                if (num == 0) {
                    cout << "Error: Division by zero is not allowed!" << endl;
                    return 1;
                }
                result /= num;
            }
        }
        // Check if character is an operator
        else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
            lastOperator = ch;  // Update last operator to the current one
        }
        // Invalid character handling
        else {
            cout << "Invalid character: " << ch << endl;
            return 1;
        }
    }
Editor is loading...
Leave a Comment