Advertisement
homer512

simple calc

Sep 2nd, 2013
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Changes relative to original post marked with comments
  2.  * Original version at http://pastebin.com/95GwtFtP
  3.  */
  4. #include <iostream>
  5. /* don't import whole namespace with 'using namespace std;'
  6.  * just select the parts you need
  7.  */
  8. using std::cin;
  9. using std::cout;
  10. using std::endl;
  11. /* include string header because string is used
  12.  * was previously included indirectly via iostream
  13.  */
  14. #include <string>
  15. using std::string;
  16. /* new dependency. See calc */
  17. #include <cctype>
  18. using std::tolower;
  19.  
  20. /* got rid of all global variables */
  21.  
  22. int calc (string op, int x, int y) {
  23.   /* convert string to lower case to simplify string matching */
  24.   for(int i = 0; i < op.length(); ++i)
  25.     op[i] = tolower(op[i]);
  26.   int d = 0;
  27.   if (op == "mult")
  28.     d = x * y;
  29.   else if (op == "div")
  30.     d = x / y;
  31.   else if (op == "add")
  32.     d = x + y;
  33.   else if (op == "sub")
  34.     d = x - y;
  35.   else
  36.     cout << "Error";
  37.  
  38.   return d;
  39. }
  40.  
  41. void printanswer(string op, int x, int y) {
  42.   int answer = calc(op, x, y);
  43.   cout << "Answer: " << answer;
  44.   /* add missing whitespaces between values */
  45.   cout << " Parameters: " << op << " " << x << " " << y;
  46.   /* add a line break */
  47.   cout << endl;
  48. }
  49.        
  50. int main() {
  51.   string op;
  52.   int x, y;
  53.   cout << "What Operation? (Mult, Div, Sub, Add)";
  54.   cin >> op;
  55.   cout << "First Number?";
  56.   cin >> x;
  57.   cout << "Second Number?";
  58.   cin >> y;
  59.   printanswer(op, x, y);
  60.   /* add return statement. Value 0 signals normal termination */
  61.   return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement