Command Line Interface

Command line calculator

Report a typo

We have a C++ program called a calculator that acts as a calculator and performs arithmetic operations based on command line arguments:

#include <iostream>
#include <cstdlib>

int main(int argc, char* argv[]) {
    if (argc != 4) {
        std::cout << "Invalid number of arguments!" << std::endl;
        return 1;
    }

    int num1 = std::atoi(argv[1]);
    int num2 = std::atoi(argv[2]);
    char op = argv[3][0];

    int result;

    switch (op) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            result = num1 / num2;
            break;
        default:
            std::cout << "Invalid operator!" << std::endl;
            return 1;
    }

    std::cout << result << std::endl;

    return 0;
}

Write the correct request to the command line (let's say we want to divide 5 by 3.)

Note: std::atoi() - is a C++ standard library function that converts a string representing an integer into an actual integer value.

Enter a short text

Create a free account to access the full topic