In: Computer Science
Note :- This code is written in C++ program.
1)It will take arguments through command line, two operands
2) It will parse the arguments stored in argv to get the operation ( + , - , * , / ) that is to be performed.
3) And then it will convert the String to Integer (stoi function) to do the arithmetic operation.
4) Final Result will be displayed.
--------------------------------------------------------------------------------------------------------------------------------------------------------
#include <iostream>
#include <string>
using namespace std;
main (int argc, char **argv)
{
std::string token;
size_t pos = 0;
std::string inputStr;
std::string delimiterPlus = "+";
std::string delimiterSub = "-";
std::string delimiterMul = "*";
std::string delimiterDiv = "/";
int FinalResult = 0;
int opr1,opr2=0;
bool operatorFlag = false;
cout << "You have entered " << argc << "
arguments:" << "\n";
for (int i = 0; i < argc; ++i)
{
cout << "argv= "<<argv[i] << "\n";
inputStr = argv[i];
}
//Addition of 2 numbers
while ((pos = inputStr.find (delimiterPlus)) !=
std::string::npos)
{
//int opr1,opr2;
token = inputStr.substr (0, pos);
//std::cout << "token Plus=" <<token <<
std::endl;
opr1=stoi(token);
operatorFlag = true;
inputStr.erase (0, pos + delimiterPlus.length ());
}
//cout << "LastInput Plus=" << inputStr <<
std::endl;
opr2=stoi(inputStr);
if(operatorFlag){
FinalResult = opr1 + opr2;
operatorFlag = false;
}
//Substraction of two numbers
while ((pos = inputStr.find (delimiterSub)) !=
std::string::npos)
{
token = inputStr.substr (0, pos);
//std::cout << "token Sub=" <<token <<
std::endl;
opr1=stoi(token);
operatorFlag = true;
inputStr.erase (0, pos + delimiterSub.length ());
}
// cout << "Opr1 Sub=" << opr1 <<
std::endl;
// cout << "LastInput Sub=" << inputStr <<
std::endl;
opr2=stoi(inputStr);
if(operatorFlag){
FinalResult = opr1 - opr2;
operatorFlag = false;
}
//Multiplication of two numbers
while ((pos = inputStr.find (delimiterMul)) !=
std::string::npos)
{
token = inputStr.substr (0, pos);
// std::cout << "token mul=" <<token <<
std::endl;
opr1=stoi(token);
operatorFlag = true;
inputStr.erase (0, pos + delimiterMul.length ());
}
//cout << "Opr1 mul=" << opr1 << std::endl;
//cout << "LastInput mul=" << inputStr <<
std::endl;
opr2=stoi(inputStr);
if(operatorFlag){
FinalResult = opr1 * opr2;
operatorFlag = false;
}
//Division of two numbers
while ((pos = inputStr.find (delimiterDiv)) !=
std::string::npos)
{
token = inputStr.substr (0, pos);
//std::cout << "token Div=" <<token <<
std::endl;
opr1=stoi(token);
operatorFlag = true;
inputStr.erase (0, pos + delimiterDiv.length ());
}
// cout << "Opr1 Div=" << opr1 <<
std::endl;
//cout << "LastInput Div=" << inputStr <<
std::endl;
opr2=stoi(inputStr);
if(operatorFlag){
FinalResult = opr1/opr2;
operatorFlag = false;
}
cout<<"Final Result= " << FinalResult
<<std::endl;
return 0;
}