Hi, I've been learning basic C++ for the past few days, and at the moment, I'm trying to make a basic 2-number, plus/minus/multiply/divide calculator.
Here's what I have (it's complete).
Basically I was wondering if anyone could recommend a quicker or shorter way of typing all of this out.
Thanks

# include <iostream>                       // My first C++ Calculator!
# include <cmath>

using namespace std;

int main()
{
    string exitoption;
    double num1=0;
    double num2=0;
    while(exitoption != "x" || exitoption != "X")
    {
    string operationselection;
    if(num1 == 0 && num2 == 0)
    {
    cout << "Welcome to basic calculator!\n";
    cout << "Do you want an addition calculator, subtraction calculator,\nmultiplication calculator, or division calculator?\n";
    }
    while(operationselection != "add" && operationselection != "sub" && operationselection == "div" && operationselection == "mult")
    {
    operationselection = "abcabc";
    cout << "(Enter add, sub, mult, or div)\n";
    cin >> operationselection;

    if(operationselection == "add")
    {
        cout << "Enter two Real numbers." << endl;
        cin >> num1 >> num2;
        cout << num1 + num2 << endl;
    }

    else if(operationselection == "sub")
    {
        cout << "Enter two Real numbers." << endl;
        cin >> num1 >> num2;
        cout << num1 - num2 << endl;
    }

    else if(operationselection == "div")
    {
        cout << "Enter two Real numbers." << endl;
        cin >> num1 >> num2;
        cout << num1 / num2 << endl;
    }

    else if(operationselection == "mult")
    {
        cout << "Enter two Real numbers." << endl;
        cin >> num1 >> num2;
        cout << num1 * num2 << endl;
    }

    else
    {
        cout << "Type one of the four choices." << endl;
    }
    }

    if(num1 == 0 && num2 == 0)
    {
        num1 = 1;
    }

    exitoption="abcabcabc";
    if(exitoption == "abcabcabc" && operationselection == "add" && operationselection == "sub" && operationselection == "div" && operationselection == "mult")
    cout << "Enter 'x' to exit, or 'c' to retry Basic calculator!\n";
    cin >> exitoption;
    if(exitoption == "x" || exitoption == "X")
    {
        cout << "You are have chosen to exit.\n";
        return 0;
    }

    while(exitoption != "x" && exitoption != "X" && exitoption != "c" && exitoption != "C")
    {
        cout << "Choose 'x' or 'c'.\n";
        cin >> exitoption;
        if(exitoption == "x" || exitoption == "X")
    {
        cout << "You are have chosen to exit.\n";
        return 0;
    }
    }
    }

    system("PAUSE");
    return 0;
}

Recommended Answers

All 14 Replies

A good first attempt :)
From your code, I can suggest some improvements:
1. NEVER use system("pause"); . See here for more information. Use std::cin.get(); instead.
2. To make typing the code shorter, you should always look to reduce repetitive code, like the following statements: cout << "Enter two Real numbers." << endl;cin >> num1 >> num2; . This can be typed once before you start your if-else structure and thats it.
3. I noted that you've used a string to accept your program's exit/continue option. A single char variable would suffice.
4. You can use a do-while loop for the program's main body. An example would be:

{ // Inside the main() function
   char exitoption;
   // your instructions/declaration code
   // ...

   do {
     // the rest of your code
   } while(exitoption != 'x');
   
   // exit message can go here

   std::cin.get();
   return 0;
}

5. What exactly do you use this statement for? : if(num1 == 0 && num2 == 0) This isn't required IMO, nor is this: if(num1 == 0 && num2 == 0) { num1 = 1; } . Just put the instruction outside the loop, so that it displays just the one time.
6. In your division option, it is better to check that num2 isn't 0, as any real number cannot be divided by zero.
7. If you want to make a calculator that evaluates whole expressions(advanced) like this: (5*2)/6-(24/4) , try implementing stringstreams, and use a stack to convert it into post-fix notation to evaluate it. See these for more details: http://www.java2s.com/Code/Cpp/Data-Structure/Afourfunctionpostfixcalculator.htm and http://www4.ncsu.edu/~awwatkin/FILES/Postfix.C

Hope this helps!

while(operationselection != "add" && operationselection != "sub" && operationselection == "div" && operationselection == "mult")

This evaluates to :
1. String is Not Equal to Add AND String is not Equal to Sub AND String is Equal to Mult AND String is Equal to Div

The Loop shouldn't even be executing as initially operationselection = ""
so the Boolean exp is

1 [B]AND [/B]1 [B]AND [/B]0 [B]AND [/B]0 = 0

and while(0) is false;

try using switch-case instead:

int myChoice;
while(1)
{
    clrscr(); //Include conio
    cout<<
    "\nEnter Choice"
    "\n1. Add"
    "\n2. Sub"
    "\n3. Mult"
    "\n4. Div"
    "\n5. Exit";
    cout<<"Choice (1/2/3/4/5): ";
    cin>>myChoice;

    switch(myChoice)
    {
        case 1:
            cout<<n1+n2;
        break;
        
        case 2:
            cout<<n1-n2;
        break;
    
        case 3:
            cout<<n1*n2;
        break;
    
        case 4:
            if(!n2)
                cout<<"Cannot divide by Zero";
            else
                cout<<n1/n2;  
        break;

        case 5:
            exit(1); //Include stdlib or process.h

        default:
            cout<<"\nWrong Choice";
    }
}

Thanks for the help, I haven't applied it much to my code, but I've made a revised version of my calculator, here it is (it works well!).

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    string exitoption;
    double num1, num2;
    string operation;
    cout << "- Welcome to basic calculator." << endl;
    cout << "- Do you want an addition, subtraction,\n  multiplication, or division calculator?" << endl;
    int x=1;
do
{
    do
    {
        do
        {
        if(x==1)
        cout << "- Enter 'add', 'sub', 'mult', or 'div'." << endl;
        cin >> operation;
        }while(operation != "add" && operation != "sub" && operation != "mult" && operation != "div");
        x=0;
        cout << "Now type in the two numbers which you wish to involve in the equation." << endl;
        cin >> num1 >> num2;

        if(operation == "add")
            cout << num1 << " plus " << num2 << " is " << num1 + num2 << endl;
        else if(operation == "sub")
            cout << num1 << " minus " << num2 << " is " << num1 - num2 << endl;
        else if(operation == "mult")
            cout << num1 << " multiplied by " << num2 << " is " << num1 * num2 << endl;
        else if(operation == "div")
            cout << num1 << " divided by " << num2 << " is " << num1 / num2 << endl;
        else
            cout << "Choose from the four supplied modes." << endl;
    }while(operation != "add" &&  operation != "sub" && operation != "mult" && operation != "div");
    x=1;

    do
    {

        if(x==1)
        cout << "You can now exit by entering 'x', or continue using basic calculator by entering 'c'." << endl;
        cin >> exitoption;
        x=0;
        if(exitoption == "x")
        {
            std::cin.get();
            return 0;
        }
        else if(exitoption != "x" && exitoption != "c")
            cout << "You did not enter 'x' or 'c'!" << endl;
        else if(exitoption == "c")
            cout << "You have chosen to reuse basic calculator." << endl;
            }while(exitoption != "x" && exitoption != "c");
            x=1;
}while(exitoption == "c");
}

No offence, but you do seem to me a fan of Rune Goldberg.
Obviously you put in a lot of effort to design that calculator, your logical thinking is commendable, but an advice: Don't over-complicate simple things. :)

Try learning switch-case, it's more suited to your code logic.

commented: Well put :) +2

Thanks for the advice.

I have actually learnt switch statements, and here's my attempt:

I got an error saying "switch quantity not an integer"

Also, one other thing I want to do with my code is to make it so when it asks you to enter two numbers (for the equation), if you enter values that aren't numbers (like "hello"), the program says "you did not enter Real numbers".
- I tried fixing this by using the isdigit() command, but it didn't work (not declared in scope), even though I added the library: <ctype.h>.

#include <iostream>
#include <cmath>
#include <ctype.h>

using namespace std;

int main()
{
    string exitoption;
    double num1, num2;
    string operation;
    cout << "- Welcome to basic calculator." << endl;
    cout << "- Do you want an addition, subtraction,\n  multiplication, or division calculator?" << endl;
    int x=1;
do
{
    do
    {
        do
        {
        if(x==1)
        cout << "- Enter 'add', 'sub', 'mult', or 'div'." << endl;
        cin >> operation;
        }while(operation != "add" && operation != "sub" && operation != "mult" && operation != "div");
        x=0;
        cout << "Now type in the two numbers which you wish to involve in the equation." << endl;
        cin >> num1 >> num2;

        // Need a stopper of entering CHARACTERS HERE, otherwise program goes crazy, (if not a Real Number)
        switch(operation)
        {
            case "add":
            cout << num1 << " plus " << num2 << " is " << num1 + num2 << endl;
            break;
            case "sub":
            cout << num1 << " minus " << num2 << " is " << num1 - num2 << endl;
            break;
            case "mult":
            cout << num1 << " multiplied by " << num2 << " is " << num1 * num2 << endl;
            break;
            case "div":
            cout << num1 << " divided by " << num2 << " is " << num1 / num2 << endl;
            break;
            default:
            cout << "Choose from the four supplied modes." << endl;
        }
    }while(operation != "add" &&  operation != "sub" && operation != "mult" && operation != "div");
    x=1;

    do
    {

        if(x==1)
        cout << "You can now exit by entering 'x', or continue using basic calculator by entering 'c'." << endl;
        cin >> exitoption;
        x=0;
        if(exitoption == "x")
        {
            std::cin.get();
            return 0;
        }
        else if(exitoption != "x" && exitoption != "c")
            cout << "You did not enter 'x' or 'c'!" << endl;
        else if(exitoption == "c")
            cout << "You have chosen to reuse basic calculator." << endl;
            }while(exitoption != "x" && exitoption != "c");
            x=1;
}while(exitoption == "c");
}

Switch can only accept integers and chars not strings.
Get rid of the nested loops, you dont need so much complication for such a simple program
You the program flow suggested by nbaztec

@willrx7etc
>> I got an error saying "switch quantity not an integer"
If you had paid attention while learning switch statements in C++, then you would have known that this control structure evaluates expressions, i.e, a numerical value, typically. A string, being a sequence of characters is not a numerical value, which is why you get that error.

>> isdigit() doesn't exist in <ctype.h>
Sometimes, this function can be found in the header <locale> Here's a typical example of a simple calculator in C++ with error checking:

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

void clearRubbish(std::istream& in) { // Accept the bad-stream
    in.clear(); // Clear the buffer
    string rubbish;
    in >> rubbish; // Remove the "bad" input from the stream and into the string
    cerr << " Invalid Input!" << endl;
}

int main()
{
    char exitoption; // Variable to let the users choose to end/continue program
    int selection;   // Variable to let the user slect the operation
    double n1, n2;   // Variables to hold the value of the input

    cout << "A Simple Calculator";
    do {
        cout << "\nOperations available:\n\t"
             << "1. Addition\n\t"
             << "2. Subtraction\n\t"
             << "3. Multiplication\n\t"
             << "4. Division\n"
             << "===========================\n"
             << "Your choice: ";
        cin >> selection;

        do {
            cout << "\nEnter the numbers below:\n\t1. ";
            cin >> n1; // Accept first number
            if(!cin.good()) { // If the standard input stream has failed (bad state)
                clearRubbish(cin); // remove the bad input from the stream
                continue;
            }
            cout << "\n\t2. ";
            cin >> n2; // Accept second number
            if(!cin.good()) { // If the standard input stream has failed (bad state)
                clearRubbish(cin); // remove the bad input from the stream
                continue;
            }
            else // No bad input received, continue program
                break;
        } while(1);
        cout << endl;

        switch(selection) {
            case 1: cout << n1 << " + " << n2 << " = " << n1+n2;
            break;
            case 2: cout << n1 << " - " << n2 << " = " << n1-n2;
            break;
            case 3: cout << n1 << " x " << n2 << " = " << n1*n2;
            break;
            case 4:
                if(!n2)
                    cerr << "\nCannot divide by zero!";
                else
                    cout << n1 << " / " << n2 << " = " << n1/n2;
            break;
            default: cerr << "\n\nOperation not supported!";
        }
        cout << "\n\nContinue program? (y/n) :: ";
        cin >> exitoption;
    } while(exitoption == 'y' || exitoption == 'Y');

    cin.get();

    return 0;
}

Well the tutorial I used to learn switch statements didn't mention that switches only support char, or int values.
That being said, maybe I need to learn basic c++ a different way :yawn:.

The only way you can learn these things is by programming. So keep practicing.

Okay, well I've just used a series of youtube tutorials on C++ to gather this basic knowledge, so now if I start practising using other random projects, and I come to something I don't know how to do, I can ask here what a good way to fill this in is?

Sure, feel free :) We'll be glad to help you in any way we can...

Search on google. There is a very good chance some one has already encountered the bug before and would have posted the detailed solution
If you cannot find any answer on google then post your question here

All right then, I'll get on with another project!

That's great! :) Please mark this thread as solved in that case ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.