Vous êtes sur la page 1sur 7

THE CALCULATOR

INTRODUCTION
In this article, I will present a calculator created in C++, with a few basic operators: +, -, * and /.
User will input numbers and operators, and as a result of our program, we will have one resulting number or
message that something went wrong.
The aim of this article is to show you, how to protect your application from some basic, most common errors that
could happened. In another words, I will present you with a few exceptions and concrete examples of situations
in which you would need to incorporate them into application.
This will decrease simplicity of the program.
What I am telling hear is, that we sometimes omit this: try, throw, catch blocks in order to make our codding more
understandable, however it would be very important to learn this techniques with time.
No, I am not telling that you will maintain your code more easily, if you don't use this important parts of C++, I
am just saying that people who write code for articles will omit them, just to keep focus on code they are writing
and algorithm they are developing.

DEFINITIONS OF THE PROBLEM


Ok, now let's agree on our application and focus we will have. The focus is on exceptions and that's it, however
some readers would find some more things interesting as well.
This one is one of the most basic techniques, that should be understandable to almost any one who like
programming.
In our program, we will input values and operations from user, till we need to stop, and present result.
Values are of a double data type, however it could be interesting to create calculator of big numbers, the really big
ones, yes those ones that are larger than long long int or long double.
It would be nice to create class of big number and use it in calculations, just for fun. Yes, that is enough
motivation for some people.
You will have four basic operations: plus, minus, multiplication and division of numbers.
At the end you will get result.
Not hard to utilize, but very important to learn how to do it.
And yes, we need few words to tell how you use program, well you input numbers and operators and if
everything is working, well, you will get results. In the case that something goes wrong you would get
appropriate message, if you don't like messages fell free to adjust them.
For more advanced users, it would be a good starting point for further betterments.

EXAMPLE
CODE:
Ok, let's see what do we have in our project after all.
There are tree files:
main.cpp,
HelperFile.h
HelperFile.cpp.
In first file, main.cpp we have our program implemented, there are a few function calls and some try except

blocks, just to protect our progeam.


Next thing we have is HelperFile.h which is file for some: definitions, exceptions classes and few functions.
In HelperFile.cpp we have our functions implemented.
Ok, now I will provide code in main.cpp
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include "HelperFiles.h"
#include <exception>
using namespace std;
int
main(int argc, char** argv) {
firstScrean();
// dNumber will be used to store numbers
// that we take from user
// dResult will be used to store results
double dNumber = 0.0,
dResult
= 0.0;
// User will input operators as well
char cOperator = '+';
try
{
inputNumber( dNumber );
dResult+= dNumber;
do
{
inputOperator( cOperator );
inputNumber( dNumber );
doOperation( dNumber, cOperator, dResult );
cout<<"Some more numbers y/n->";
char cRespond; cin>>cRespond;
if( ( cRespond == 'y' ) || ( cRespond == 'Y' ) ) continue;
break;
}
while(true);
}
catch( Error_Wrong_Operator )
{
cout<<"Wrong operator";
exit(EXIT_FAILURE);

}
catch( Error_Zero_Division )
{
cout<<"Zero division not alowed";
exit(EXIT_FAILURE);
}
catch( Error_Bad_Number )
{
cout<<"We don't acept bad numbers";
exit(EXIT_FAILURE);
}
catch( bad_exception )
{
cout<<"Bad Exception";
exit(EXIT_FAILURE);
}
catch( exception )
{
cout<<"Exception ";
exit(EXIT_FAILURE);
}
//Now let's present our results
try
{
if ( isinf( dResult ) )
throw Error_Bad_Results();
if ( isnan( dResult ) )
throw Error_Bad_Results();
if( dResult == POSITIVE_BIG_DOUBLE )
throw Error_Bad_Results();
if( dResult == NEGATIVE_BIG_DOUBLE )
throw Error_Bad_Results();
cout<<"The result is = "
<<dResult
<<endl;
}
catch( Error_Bad_Results )
{
cout<<"You have bad results";
exit(EXIT_FAILURE);
}
catch( bad_exception )
{
cout<<"Bad Exception";
exit(EXIT_FAILURE);
}
catch( exception )

{
cout<<"Exception";
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
Next thing we will need to create in our calculator project, is HelperFile.h.
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <exception>
#define NUMBER_BUFFER 15
#define POSITIVE_BIG_DOUBLE 1.7976931348623157e+308
#define NEGATIVE_BIG_DOUBLE -POSITIVE_BIG_DOUBLE
using namespace std;
class Error_Wrong_Operator : public exception{};
class Error_Bad_Number

: public exception{};

class Error_Zero_Division

: public exception{};

class Error_Bad_Results

: public exception{};

void firstScrean( void );


int inputNumber ( double& );
int inputOperator( char& );
int doOperation ( double& , char& , double& );
Next file we need for our project, is implementation of our functions:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <exception>
using namespace std;
void
firstScrean( void )
{

cout<<"This is a simple calculator."<<endl


<<"You will have: +, -, *, and /"<<endl
<<"as operators in calcualations"<<endl;
system("PAUSE");
system("CLS");
}
int
inputNumber( double& dNumber )
{
char cInputNumber[ NUMBER_BUFFER ];
cout<<"Input a numbe->"; cin>>cInputNumber;
int iStartPoint;
if( isdigit( cInputNumber[0] ) )
iStartPoint= 0;
else if( cInputNumber[0] == '+')
iStartPoint= 1;
else if( cInputNumber[0] == '-')
iStartPoint= 1;
else
throw Error_Bad_Number();
bool bFirstDot = true;
for(int i = iStartPoint;
i< strlen( cInputNumber );
i++)
{
if( isdigit( cInputNumber[i] ) ) continue;
if( ( cInputNumber[i] == '.') &&
( bFirstDot ) )
{
bFirstDot = false;
continue;
}
throw Error_Bad_Number();
}
dNumber = atof( cInputNumber );
}
int
inputOperator( char& cOperator)
{
cout<<"Input operator->"; cin>>cOperator;
if( !( ( cOperator == '+' ) ||
( cOperator == '-' ) ||
( cOperator == '*' ) ||
( cOperator == '/' ) ) )
throw Error_Wrong_Operator();
}

int
doOperation( double& dNumber,
char& cOperator,
double& dResult )
{
switch( cOperator )
{
case '+': dResult += dNumber;
break;
case '-': dResult -= dNumber;
break;
case '*': dResult *= dNumber;
break;
case '/':
if( dNumber == 0.0)
{
cout<<"Can't divide by zero!!"
<<endl;
throw Error_Zero_Division();
system("PAUSE");
exit(EXIT_FAILURE);
}
dResult /= dNumber;
}
}
In next part, we will analyze some parts of the code.
ANALYZE OF CODE:
So, let's consider our main program, in which we have some interesting things to explain. After, we have
directives to our compiler we will need to have few initializations, this part is very obvious and code is
commented, so we will not go into details.
After, we have finished all initializations we move into major code, we have one try catch block that is protecting:
input of numbers, input of operators and calculations. I have, implemented inputs and calculations in one do
while loop, however it would be possible to have some different implementations, and I would recommend you
to try them as well, it will improve your codding skills. Some intrepid programmers would create the better catch
block.
Next thing we need to do, is to protect and present our results to user.
Now, we will move to our helper file. There you will find few interesting things, first of all there is definition of
few macros, you could create your constants, our you could use some that are defined in float.h also.
Next thing you would find are definitions of error classes. In case that you prefer to use struct, you could try that
as well.
Beside this, I would like to mention that this could be implemented in other ways as well, and also you have the
ones that are specific to operating system that might be used in your case.
There are few more standard exceptions that could be used in this situation also, to develop this program I have
used Dev C++.
Now, we have definitions of our functions.

Implementation of functions are in our HelperFiles.cpp and we will discus them now.
The first function will be used to present some form of explanation to an user, it is not very interesting, but don't
forget to use it any way.
The second function is very important, it could be used in few more situations, so it would be good idea to keep it
some place where you would be able to find it in the case you might need it.
So, how does it work, first you create buffer for string in style of C, that is place to keep input from user, and due
to the fact that some users are inputing bad numbers, we need to analyze that string, in order to create more better
solution I would recommend you to include number in exponential form as well, then you could have two
functions, one to check regular number and one to check if number is in an exponential form. Then, you would
test if something is like this if (( regularNumber(cInputNumber) || (exponentialNumber(cInputNumber)), or you
would try ternary operator.
This function is not hard to understand, all you need is to check the first character, if it is acceptable it would be:
number, + or -.
After, we have established this, we need to check our cInputNumber, if you have inputed correct number there
would be zero or one '.', but not any more, the rest of characters would be numbers.
In the case that we have bad input we throw error object, that is handled in main program.
The next function, inputOperator will test inputed character for operation, this might be bad point of application,
in the case that you input more characters, program will ignore the rest of them, it is something to improve in
professional version of the program.
Although, this might look bad, in program with graphical user interface you would be able to limit this length to
one character very easy. The problem of this program is also that it would be way easier to implement it with
graphical interface.
After this three functions, we have doOperation in which we have appropriate operation implemented, it is
important to prevent division by zero, just because that could happened you should throw one exception, that gets
handled in main function as well.
So, now we would create small digression, in main function we have protected presentation of our results, it
would be easy to imagine some function created from this part of the code.I would recommend you to utilize this
part on your own as a part of exercise.
Hope, this was enough explanation, it would be good for exercise any way, just think and try to improve it.

CONCLUSION
Now, I hope that you have figure out how try catch block gets used in this example.
For some people it might be very useful, but if you are new in this area you might need some additional readings
as well. It would be good direction for further studies. Ok, now is time to have fun codding.

Vous aimerez peut-être aussi