Thread: Console Calc
View Single Post
Old Sep 15th, 2005, 12:27 PM   #14
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
As mentioned previously, I would not implement a calculator this way. This does, however, afford protection. On another point, when outputting, you will want to output an "endl" instead of a "\n" at least at some point. It causes the output to be flushed. One doesn't always see a failure to flush, because other conditions cause it to happen, but be prepared. You can always flush overtly, but the endl does it for you.

#include <iostream>
#include <string>

using namespace std;

int ohHell (string badNews)
{
    cerr << badNews << endl;
    return 1;
}
int main (int argc, char *argv [])
{
    int opchoice;
    int numberone;
    int numbertwo;
    int answer;
    bool failure = false;

    // Choose your operation
    cout << "Choose your operation\n\n1 - Multiplication\n2 - Subtraction\n3 - Addition\n4 - Division\n\n"<<endl;
    cin >> opchoice;
    if (!cin.good ()) return ohHell ("Input failure on operator choice");
	
	cout << "\nPlease input the first number\n\n";
    cin >> numberone;
    if (!cin.good ()) return ohHell ("Input failure on first operand");

    cin.sync ();
    cout << "\n\nPlease input the second number\n\n";
    cin >> numbertwo;
    if (!cin.good ()) return ohHell ("Input failure on second operand");

	switch( opchoice)
	{
	case 1: 
		// Multiplication
       answer = numberone * numbertwo;
	   break;
	case 2:
	   // Subtraction
		answer = numberone - numbertwo;
		break;
    // Addition
    case 3:
		answer = numberone + numbertwo;
		break;    
	case 4:
		//division
		answer = numberone / numbertwo;
    default:
        failure = true;

	}
    if (failure) cout << "No operation was performed";
    else cout << "\nThe final answer is " << answer << endl;

    cin.get();
    return 0;
}
Notice that the protection didn't unduly lengthen the code.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote