- Joined
- Apr 22, 2005
- Sythe Gold
- 23
- Messages
- 7,825
This does not provide argument checking and will only perform operations if all the arguments are one-digit numbers as it only reads 1 character for number arguments. But if you know how to use the string class, this shouldn't be difficult to understand, etc....
Example usage:
Code:
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
string str1;
while(true)
{
str1.clear();
cout << "Calc> "; getline(cin,str1);
if(str1.substr(0,3)=="ADD")
{
string temp = str1.substr(4,1);
int a = atoi(temp.c_str());
temp.clear();
temp = str1.substr(6,1);
int b = atoi(temp.c_str());
int c = a + b;
cout << a+b << endl;
}
else if(str1.substr(0,3)=="SUB")
{
string temp = str1.substr(4,1);
int a = atoi(temp.c_str());
temp.clear();
temp = str1.substr(6,1);
int b = atoi(temp.c_str());
int c = a - b;
cout << c << endl;
}
else if(str1.substr(0,3)=="MUL")
{
string temp = str1.substr(4,1);
int a = atoi(temp.c_str());
temp.clear();
temp = str1.substr(6,1);
int b = atoi(temp.c_str());
int c = a * b;
cout << c << endl;
}
else if(str1.substr(0,3)=="DIV")
{
//note that i'm using float for division, not int
string temp = str1.substr(4,1);
float a = atoi(temp.c_str());
temp.clear();
temp = str1.substr(6,1);
float b = atoi(temp.c_str());
float c = a/b;
cout << c << endl;
}
else if(str1.substr(0,3)=="POW")
{
string temp = str1.substr(4,1);
int a = atoi(temp.c_str());
temp.clear();
temp = str1.substr(6,1);
int b = atoi(temp.c_str());
int c = 1;
if(b>=1)
{
for(int i = 0; i < b; i++)
{
c*=a;
}
}
cout << c << endl;
}
else if(str1.substr(0,3)=="BYE")
{
exit(0);
}
else
{
cout << "Invalid command, must be ADD, SUB, MUL, DIV, POW or BYE" << endl;
}
}
return 0;
}
Code:
Calc> ADD 2 3
5
Calc> SUB 8 3
5
Calc> MUL 2 8
16
Calc> DIV 6 2
3
Calc> POW 2 3
8
Calc> BYE













