C++ Calculator

Dak914's Avatar, Join Date: May 2008
Go4Expert Member
I have just begun programming in C++, coming into it from Java. I have noticed that making a calculator that doesnt crash is, in a sense, hard for any newbie beginner. For all the other newbie beginners like me, I have developed a simple and relatively easy to understand calculator. It doesnt use any graphics, just a terminal. Before you continue, one of the included files, called sstream, uses something called stringstream to convert data from a string to a int, double, float, ect. This is what I am using to prevent the program from crashing, so if you input anything other than a number or operator, you will get a numberE+number or the number 0. This is a relatively large script because I wanted to make it easy to understand. I know I could have used more comments. Well, finally, here is that code.

fix: Uh, nevermind, I am not completely sure on how I get the code into the post so you can just download it from here...

http://dak914.t35.com/calc.cpp

This site will be dedicated to my source code files from now on...Just in case you were wondering...

Learn.
~Connor
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Use [ code ] and [ /code ] (without the spaces). For example, entering
[ code ]
double calc (string a, string oper, string b)
{
double c;
double d;
double answer;
[ /code ]

gives the result:
Code:
double calc (string a, string oper, string b)
 {
 double c;
 double d;
 double answer;
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
http://www.go4expert.com/misc.php?do=bbcode#code should also help
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
calc() can be streamlined quite a lot, for example, if oper is char (not char*) rather than string:
Code:
switch (oper)
{
case '+': return c+d;
case '-': return c-d;
default: return 0;
}
It's not necessary to assign the result of a calculation to a variable whose only purpose is to return that value; you can juse use return <expr>;

In terms of improving the program, there's not much that else can be done within the existing functionality. It's very simple, the only improvements really can be the addition of new features: other operators, functions, memory/memories etc. Have a look at Windows Calc for other inspiration.
0
Dak914's Avatar, Join Date: May 2008
Go4Expert Member
Oh, I get it now. Well thanks a ton. Like I said I am new to C++. I am currently working on the card game called War. I read up a little more on the switch thing. I am going to use my website for all my code so you can download it and view it in your own preferred environment, such as notepad or Visual C++. Thanks again for the tips
~Connor