Thread: A Basic Calculator.

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    151

    A Basic Calculator.

    Here is my code:
    Code:
    //calc.h
    #include <iostream>
    #include <cmath>
    
    using namespace std;
    
    inline void operations()
    {
    	cout<<"x,/,+,-,^,s2(square root)\n";
    }
    
    float math()
    {
    	float x;
        float y;
        char a;
    	float answer;
       cout<<"enter an problem (4o for operations)";
       cin>> x >> a >> y;
    
    	switch (a){
    	case 'o':
    		answer = (char) 0;
    	    operations();
    		break;
    	case 's':
    		answer = sqrt (x);
    		break;
    	case 'x':
    		answer = x*y;
    		break;
    	case '/':
    		answer = x/y;
    		break;
    	case '+':
    		answer = x+y;
    		break;
    	case '-':
    		answer = x-y;
    		break;
    	case '^':
    		answer = pow (x,y);
    		break;
    	}
    	return answer;
    }
    Code:
    //calculator test.cpp
    #include <iostream>
    #include <dos.h>
    #include "calc.h"
    
    using namespace std;
    
    int main()
    { 
    	float answer = math();
    
    	cout<< answer <<"\n";
    
    	system("pause");
    }
    I have two problems:
    1)I have to type 4o twice for t to show the operations.
    2)I don't want to have to press 4 (well any other number) for it to show the operations.

  2. #2
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    Read the input as a line using getline(), then parse it using stringstream (after checking for 'o').

  3. #3
    Registered User
    Join Date
    Nov 2009
    Posts
    151
    Can you give me an example?

  4. #4
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    Code:
    string line;
    getline(cin, line);
    if (line.at(0) == 'o') {
    ...
    } else {
    stringstream ss(line);
    ss >> x >> a >> y;
    }

  5. #5
    Registered User
    Join Date
    Nov 2009
    Posts
    151
    thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Basic Calculator I made check it out if you want...
    By Sshakey6791 in forum C++ Programming
    Replies: 8
    Last Post: 01-08-2009, 12:20 AM
  2. Basic Calculator
    By Surge in forum C Programming
    Replies: 18
    Last Post: 12-02-2006, 10:20 PM
  3. Basic calculator program in C++
    By linkofazeroth in forum C++ Programming
    Replies: 70
    Last Post: 08-28-2005, 04:23 PM
  4. need help with my basic c++ calculator
    By iCouch_Potato in forum C++ Programming
    Replies: 4
    Last Post: 03-24-2004, 06:23 PM