This is a pretty basic program that adds, subtracts, multiplies, or divides 2 numbers based on user input. I used a #define to create a shortcut for std::cout and the same can be done for std::endl if you wish to reduce how much typing you have to do.
Another interesting function I used is isDigit(x) which is part of the ctype.h library. It will return 0 if x is not a digit and something other than 0 if it is a digit. The reason I looped through the entire string is that if someone were to input 5gg and I only checked the first character it would come back as true and my atoi conversion would pick it up as only a 5, which could give unintended results. Since argv[] can be treated as a string I know it will end with a null byte and I just loop through to check every character till I reach the end.
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<ctype.h>
#define COUT std::cout
int main(int argc, char *argv[])
{
bool valid;
if (argc == 4)
{
for(int i = 0; argv[1][i] != '\0'; i++) //checks if 1st argument is all digits
{
if(!isdigit(argv[1][i]))
valid = false;
}
for(int i = 0; argv[3][i] != '\0'; i++) //checks if 3rd argument is all digits
{
if(!isdigit(argv[3][i]))
valid = false;
}
if(valid)
{
double leftSide = atof(argv[1]);
double rightSide = atof(argv[3]);
//checks if 3rd argument is a valid operator then calculates - else prints error message
if(strcmp(argv[2], "+") == 0)
COUT << leftSide + rightSide << std::endl;
else if(strcmp(argv[2], "-") == 0)
COUT << leftSide - rightSide << std::endl;
else if(strcmp(argv[2], "x") == 0)
COUT << leftSide * rightSide << std::endl;
else if(strcmp(argv[2], "/") == 0)
COUT << leftSide / rightSide << std::endl;
else
COUT << "bm <number> <+-x/> <number>" << std::endl;
}
else
COUT << "bm <number> <+-x/> <number>" << std::endl;
}
else
COUT << "bm <number> <+-x/> <number>" << std::endl;
return 0;
}