DEV Community

Kerimova_Manzura
Kerimova_Manzura

Posted on

C++ Calculator.

Hello, today i would like to show you how to create a calculator in C++.

#include <iostream>
#include <vector>
#include <string>

class Calculator {
private:
    std::vector<std::string> history;

public:
    Calculator() {}

    void Run() {
        while (true) {
            DisplayMenu();
            std::string choice;
            std::getline(std::cin, choice);

            if (choice == "1") {
                PerformCalculation();
            } else if (choice == "2") {
                ViewHistory();
            } else if (choice == "3") {
                std::cout << "Exiting the calculator. Goodbye!\n";
                return;
            } else {
                std::cout << "Invalid choice. Please choose again.\n";
            }
        }
    }

private:
    void DisplayMenu() {
        std::cout << "\n===== Calculator Menu =====\n";
        std::cout << "Hey bro, pick one action:\n";
        std::cout << "1. Perform a calculation\n";
        std::cout << "2. View calculation history\n";
        std::cout << "3. Exit\n";
    }

    void PerformCalculation() {
        try {
            std::cout << "Enter the first number: ";
            double num1;
            std::cin >> num1;

            std::cout << "Enter the second number: ";
            double num2;
            std::cin >> num2;

            std::cout << "Pick one of them: (+, -, *, /): ";
            char operation;
            std::cin >> operation;

            double result = 0;
            std::string operationString;

            switch (operation) {
                case '+':
                    result = num1 + num2;
                    operationString = "+";
                    break;
                case '-':
                    result = num1 - num2;
                    operationString = "-";
                    break;
                case '*':
                    result = num1 * num2;
                    operationString = "*";
                    break;
                case '/':
                    if (num2 == 0) {
                        std::cout << "Error: Division by zero.\n";
                        return;
                    }
                    result = num1 / num2;
                    operationString = "/";
                    break;
                default:
                    std::cout << "Error: Invalid operation.\n";
                    return;
            }

            std::cout << "Result: " << num1 << " " << operationString << " " << num2 << " = " << result << "\n";
            history.push_back(std::to_string(num1) + " " + operationString + " " + std::to_string(num2) + " = " + std::to_string(result));
        }
        catch (const std::invalid_argument& e) {
            std::cout << "Invalid input format. Please enter valid numbers.\n";
        }
        catch (const std::out_of_range& e) {
            std::cout << "Number is too large or too small for double type.\n";
        }
        catch (...) {
            std::cout << "An unknown error occurred.\n";
        }

        // Clear input buffer
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

    void ViewHistory() {
        std::cout << "\n===== Calculation History =====\n";
        if (history.empty()) {
            std::cout << "No calculations recorded yet.\n";
        } else {
            for (size_t i = 0; i < history.size(); ++i) {
                std::cout << i + 1 << ". " << history[i] << "\n";
            }
        }
    }
};

int main() {
    Calculator calculator;
    calculator.Run();
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

So this is C++ calculator code. Let me explain it on by one.

  1. Standard input and output: C++ uses std::cin for input and std::cout for output, and std::getline for reading strings.

  2. Exceptions: Exception handling in C++ is done using try and catch constructs. For different types of errors (for example, incorrect number format or division by zero), appropriate exception types are used.

  3. Vector for history: Instead of List, C# uses std::vectorstd::string to store the history of calculations.

  4. Clearing the input buffer: To prevent problems with extra input after numbers, use std::cin.ignore(std::numeric_limitsstd::streamsize::max(), '\n');.

If we use a function, it will be easier to write code. To do this, we create a function (void) and then write the code we need. After that we just call the function where we need it. After that you don't need to write a lot of code, but just call the function.

class Calculator {
private:
    std::vector<std::string> history;

public:
    Calculator() {}

    void Run() {
        while (true) {
            DisplayMenu();
            std::string choice;
            std::getline(std::cin, choice);

            if (choice == "1") {
                PerformCalculation();
            } else if (choice == "2") {
                ViewHistory();
            } else if (choice == "3") {
                std::cout << "Exiting the calculator. Goodbye!\n";
                return;
            } else {
                std::cout << "Invalid choice. Please choose again.\n";
            }
        }
    }

private:
    // Methods of the Calculator class.
};

Enter fullscreen mode Exit fullscreen mode
  1. Private field history: This is a vector (std::vectorstd::string) that is used to store the history of calculations as strings.

  2. Run() method: This method starts the main loop of the program. It displays the calculator menu (DisplayMenu()), reads the user's choice and calls the appropriate method (PerformCalculation(), ViewHistory()), or terminates the program if the user chooses to exit.

void DisplayMenu() {
    std::cout << "\n===== Calculator Menu =====\n";
    std::cout << "Hey bro, pick one action:\n";
    std::cout << "1. Perform a calculation\n";
    std::cout << "2. View calculation history\n";
    std::cout << "3. Exit\n";
}

Enter fullscreen mode Exit fullscreen mode

This method displays a calculator menu with three options: perform a calculation, view calculation history, and exit the program.

void PerformCalculation() {
    try {
        std::cout << "Enter the first number: ";
        double num1;
        std::cin >> num1;

        std::cout << "Enter the second number: ";
        double num2;
        std::cin >> num2;

        std::cout << "Pick one of them: (+, -, *, /): ";
        char operation;
        std::cin >> operation;

        double result = 0;
        std::string operationString;

        switch (operation) {
            case '+':
                result = num1 + num2;
                operationString = "+";
                break;
            case '-':
                result = num1 - num2;
                operationString = "-";
                break;
            case '*':
                result = num1 * num2;
                operationString = "*";
                break;
            case '/':
                if (num2 == 0) {
                    std::cout << "Error: Division by zero.\n";
                    return;
                }
                result = num1 / num2;
                operationString = "/";
                break;
            default:
                std::cout << "Error: Invalid operation.\n";
                return;
        }

        std::cout << "Result: " << num1 << " " << operationString << " " << num2 << " = " << result << "\n";
        history.push_back(std::to_string(num1) + " " + operationString + " " + std::to_string(num2) + " = " + std::to_string(result));
    }
    catch (const std::invalid_argument& e) {
        std::cout << "Invalid input format. Please enter valid numbers.\n";
    }
    catch (const std::out_of_range& e) {
        std::cout << "Number is too large or too small for double type.\n";
    }
    catch (...) {
        std::cout << "An unknown error occurred.\n";
    }

    // Clear input buffer
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Enter fullscreen mode Exit fullscreen mode

This method performs a calculation depending on the selected operation (+, -, *, /). It asks the user for two numbers and an operation, processes them depending on the choice, then displays the result on the screen and adds a line with the expression and result to history. Exception handling occurs for invalid number input format or division by zero.

void ViewHistory() {
    std::cout << "\n===== Calculation History =====\n";
    if (history.empty()) {
        std::cout << "No calculations recorded yet.\n";
    } else {
        for (size_t i = 0; i < history.size(); ++i) {
            std::cout << i + 1 << ". " << history[i] << "\n";
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

This method displays the history of all previous calculations on the screen. If the history is empty, a corresponding message is displayed.

int main() {
    Calculator calculator;
    calculator.Run();
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

This function creates an object of the Calculator class, calls the Run() method to run the calculator, and returns 0, indicating successful completion of the program.

This code is an example of a simple C++ calculator that runs in the console. It demonstrates the use of a vector to store a history of calculations, process user input and display results on the screen, and handle exceptions to improve program reliability.

Top comments (0)