1: //simple_calc.cpp 3: #include <iostream> 4: #include <string> 5: #include <sstream> 6: using namespace std; 8: int main(int argc, char* argv[]) 9: { 10: if (argc == 1) 11: { 12: cout << "\nThis program is a very simple calculator which can " 13: "add, subtract, multiply, or\ndivide two integers. The " 14: "expression to be evaluated, including both operands\nand " 15: "the operator, is read from the command line and put into " 16: "an input string\nstream object, from which the individual " 17: "parts of the expression are then read\nas tokens in an " 18: "input stream in the same way they would be read from any " 19: "other\ntext input stream, such as cin." 20: 21: "\n\nSample usage:" 22: "\nsimple_calc 1 + 2" 23: "\n1 + 2 = 3"; 24: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 25: return 0; 26: } 28: //Create a string containing the command-line expression 29: string expression; 30: for (int i=1; i<argc; i++) expression += argv[i]; 32: //Create an "input string stream" from that string 33: istringstream iss(expression); 35: //Read the arithmetic expression from the "input string stream" in 36: //the same way it would be read from the keyboard or a textfile: 37: int firstOperand, secondOperand; 38: char op; 39: iss >> firstOperand >> op >> secondOperand; 41: //Evaluate the expression, then display the expression and 42: //its value: 43: int result; 44: switch (op) 45: { 46: case '+': result = firstOperand + secondOperand; break; 47: case '-': result = firstOperand - secondOperand; break; 48: case '*': result = firstOperand * secondOperand; break; 49: case '/': result = firstOperand / secondOperand; break; 50: } 51: cout << firstOperand << " " << op << " " << secondOperand 52: << " = " << result << endl; 53: }