Tuesday, March 31, 2026

Simple Calculator || 14 Beginner Level C++ Projects

Summary: 

A robust, console-based arithmetic engine designed to perform fundamental mathematical operations while maintaining high data integrity. This project serves as a foundational exercise in implementing the Model-View-Controller (MVC) pattern within a procedural-object-oriented hybrid structure, specifically optimized for the MinGW/GCC toolchain.

Learning Objectives:

  • Encapsulation: Implementing a logic class to separate mathematical operations from I/O.

  • Input Validation: Mastering the use of std::cin.clear() and std::cin.ignore() to prevent infinite loops on invalid data.

  • Stream Formatting: Using <iomanip> for professional decimal precision in scientific outputs.

The Source Code

This code is optimized for Code::Blocks. It includes necessary headers for buffer management and precision control.

#include <iostream>
#include <limits>   // Required for clearing input buffers
#include <iomanip>  // Required for setprecision

using namespace std;

// Logic Layer: The Calculator Class
class Calculator {
public:
    double add(double a, double b) { return a + b; }
    double subtract(double a, double b) { return a - b; }
    double multiply(double a, double b) { return a * b; }
    double divide(double a, double b) {
        if (b == 0) throw "Division by zero error!";
        return a / b;
    }
};

// Interface Layer: Utility functions
void clearBuffer() {
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

int main() {
    Calculator calc;
    int choice;
    double num1, num2;

    cout << fixed << setprecision(2); // Set global precision to 2 decimal places

    while (true) {
        cout << "\n===============================" << endl;
        cout << "   PRECISION CALC-ARCHITECT    " << endl;
        cout << "===============================" << endl;
        cout << "1. Addition (+)\n2. Subtraction (-)\n3. Multiplication (*)\n4. Division (/)\n5. Exit" << endl;
        cout << "Enter choice: ";

        if (!(cin >> choice)) {
            cout << "Invalid input! Please enter a number (1-5)." << endl;
            clearBuffer();
            continue;
        }

        if (choice == 5) break;
        if (choice < 1 || choice > 5) {
            cout << "Out of range! Select 1-5." << endl;
            continue;
        }

        cout << "Enter first number: ";
        while (!(cin >> num1)) {
            cout << "Error: Enter a valid number: ";
            clearBuffer();
        }

        cout << "Enter second number: ";
        while (!(cin >> num2)) {
            cout << "Error: Enter a valid number: ";
            clearBuffer();
        }

        try {
            switch (choice) {
                case 1: cout << "Result: " << calc.add(num1, num2) << endl; break;
                case 2: cout << "Result: " << calc.subtract(num1, num2) << endl; break;
                case 3: cout << "Result: " << calc.multiply(num1, num2) << endl; break;
                case 4: cout << "Result: " << calc.divide(num1, num2) << endl; break;
            }
        } catch (const char* msg) {
            cerr << "MATH ERROR: " << msg << endl;
        }
    }

    cout << "Program terminated safely." << endl;
    return 0;
}

Execution Trace (Sample Session)

===============================
  PRECISION CALC-ARCHITECT   
===============================
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
5. Exit
Enter choice: 1

[HAPPY PATH]
Enter first number: 12.5
Enter second number: 7.25
Result: 19.75

===============================

Enter choice: 4

[ERROR HANDLING - MATH]
Enter first number: 10
Enter second number: 0
MATH ERROR: Division by zero error!

===============================

Enter choice: ABC

[ERROR HANDLING - INPUT]
Invalid input! Please enter a number (1-5).

Academic "Learning Corner"

1. The MinGW "Buffer Problem"

In many IDEs like Code::Blocks, if a user enters a character (like 'A') into an integer variable, the std::cin stream enters a fail state. Subsequent calls to cin will be ignored, often resulting in an infinite loop. We solve this using:

  • cin.clear(): Resets the error flags.

  • cin.ignore(...): Discards the "junk" characters still sitting in the keyboard buffer.

2. Precision Formatting

By using std::fixed and std::setprecision(2), we ensure the output looks like a professional financial or scientific tool (e.g., 5.00 instead of 5), which is critical for user experience in technical software.


eBook ‘14 Beginner Level C++ Projects’ purchase Link: Google Play Store  || Google Books

eBook ‘14 Beginner Level C++ Projects’ Promotional Link: 

Level Up Your Coding Skills: Master C++ with 14 Hands-On Academic Projects! 


For all 2026 published articles list: click here

...till the next post, bye-bye & take care