C++ calculator displays and extra 0 in the end - c++

I am having this problem with my calculator I made. See, when I type in a calculation it always adds a 0 to the end. I don't know how to fix this do you have any ideas?
Here's the code:
#include <iostream>
using namespace std;
void Input(float &x, float &y);
float a = 1.0, b = 1.0, result;
char op;
int main() {
cout << "Welcome to Foxy's calculator" << endl;
cout << "----------------------------" << endl;
cout << "Please input a calculation operation (eg. 1+1): ";
cin >> a >> op >> b;
Input(a, b);
cout << result << endl;
system("pause");
return 0;
}
void Input (float &x, float &y) {
a = x;
b = y;
switch (op)
{
case '+':
cout << x + y;
break;
case '-':
cout << x - y;
break;
case '*':
cout << x*y;
break;
case '/':
cout << x / y;
break;
default:
cout << "Error! Operator is not correct" << endl;
cout << "Please input your calculation with a proper operator: ";
cin >> a >> op >> b;
}
}

result is a global static variable that gets zero - initialized and is never changed. So cout << result << endl; will always print "0". To fix this you should make a, b, result and op local to main (global variables are bad), pass a, b andop to calculating function and store returned calculation result in result. It will look something like this:
float result = Input(a, b, op);
cout << result << endl;

You call cout << result << endl; in the caller. and result is always 0. This is because it is never explicitly set to anything and the C++ compiler kindly zero-initialises it since it's at global scope.
In such instances, your line by line debugger is your best friend. The fact that you've mashed up your 1) input, 2) calculation, and 3) output stages is not helping: ideally they should all be separate parts of your program.

Remove cout << result << endl;

Related

How to check if input is valid and keep asking for input if it's not

Can anybody please explain why this while loop is not working properly?
#include <iostream>
using namespace std;
void ask_user(int a, int b){
char choice = ' ';
while(choice != 'q' && choice != 'a' && choice != 's' && choice != 'm'){
cout << "choose operation" << endl;
cout << "a to add, s to subtract, m to multiply and q to quit" << endl;
cout << "----------------------------" << endl;
cin >> choice;
switch(choice){
case 'a' : cout << "a + b = " << a + b;
break;
case 's' : cout << "a - b = " << a + b;
break;
case 'm' : cout << "a * b = " << a + b;
break;
case 'q' : break;
default: cout << "please Enter a valid choice " << endl;
}
}
}
int main(){
ask_user(7, 9);
return 0;
}
If I enter p for exemple which is not valid then it works fine and asks for valid input again,
but if I enter pp that's when it starts bugging and prints the message twice. If I enter ppp it
prints three times etc...
First thing, you have a misunderstanding of how switch works. Each case must end with break statement so that the following one won't get executed.
Which means that a break will break the switch, not the while.
But the main issue is that the logic of your program is wrong.
You should not loop over the validity of the given input, let the switch statement handle that in the default clause.
Instead you should loop over a flag that will be set when the user press the q key.
So considering you have the following functions defined to respectively display the menu and ask for the operands to operate on (defined for code readability):
void display_menu(char & choice)
{
std::cout << "Operation:\na: Addition\nm: Multiplication\ns: Substraction\nq: Quit\n";
std::cin >> choice;
}
void ask_operands(int & a, int & b)
{
std::cout << "\na ?";
std::cin >> a;
std::cout << "\nb ?";
std::cin >> b;
std::cout << '\n';
}
The logic of your code can be then rewritten as:
int main()
{
bool quit = false;
char choice;
int a, b;
ask_operands(a, b); // Ask the user which operands to use
while(!quit) // loop over the flag
{
display_menu(choice);
switch(choice)
{
case 'a': std::cout << (a+b);
break;
case 'm': std::cout << (a*b);
break;
case 's': std::cout << (a-b);
break;
case 'q': std::cout << "Exiting...";
quit = true; // Set the flag to false
break;
default: std::cout << "Invalid choice, try again."; //Here you handle the invalid choices (i.e. let the loop iterate again)
}
std::cout << '\n';
}
return 0;
}
Live example
Note: If you want the user to be able to change the value of the operands at each iteration, just move the ask_operands(a, b); call inside the loop.

How to make a loop start from beginning in C++?

I am writing a program in C++ which takes numbers input and it adds substracts divides, and multiplies. In the code when I want the switch case statement to run infinitely until the user presses 5 to exit the program. Please help me. Whenever I am writing the while(true) it is infinitely showing the output.
#include <iostream>
using namespace std;
class SimpleCalculator
{
protected:
private:
int num1, num2;
public:
int add(int a, int b)
{
num1 = a;
num2 = b;
return a + b;
}
int diff(int a, int b)
{
num1 = a;
num2 = b;
return a - b;
}
int quo(int a, int b)
{
num1 = a;
num2 = b;
return a / b;
}
int pro(int a, int b)
{
num1 = a;
num2 = b;
return a * b;
}
};
int main()
{
int n1, n2;
cout << "Enter the value of the number 1: ";
cin >> n1;
cout << "Enter the value of the number 2: ";
cin >> n2;
SimpleCalculator o1;
int input;
cout << "Enter your number: ";
cin >> input;
while (true)
{
switch (input)
{
case 1:
cout << o1.add(n1, n2) << endl;
break;
case 2:
cout << o1.diff(n1, n2) << endl;
break;
case 3:
cout << o1.pro(n1, n2) << endl;
break;
case 4:
cout << o1.quo(n1, n2) << endl;
break;
case 5:
break;
default:
cout << "Invalid entry" << endl;
break;
}
}
return 0;
}
You have two main issues:
The user input requests must be part of the loop since you want them to be repeated at every iteration (i.e. the user needs to make a choice at every iteration).
You forgot to exit the loop in the case 5: statement.
[Optional] Your application is lacking a user menu (the user can't guess what he has to do)
Note: I would advise you to split your code into several functions so that it would be clearer to read and easier to organize.
Note 2: You don't need to use a class for such basic operations, the members are not really needed, you can directly return the result of the operation. My advice would be to define the functions as free functions inside a namespace or as static members of your class if you really want to.
Example:
First let's define the calculation functions:
int add(int a, int b) {return a+b;}
int sub(int a, int b) {return a-b;}
int pro(int a, int b) {return a*b;}
int quo(int a, int b) {return a/b;}
Then we define a function to ask for user inputs:
void ask_user_input(int & lhs, int & rhs)
{
std::cout << "Enter the first operand: ";
std::cin >> lhs;
std::cout << "Enter the second operand: ";
std::cin >> rhs;
}
Finally we define a function to display the user menu:
void display_menu()
{
std::cout << "\n--- Calculator ---\n";
std::cout << "1. Addition\n2. Substraction\n3. Multiplication\n4. Division\n5. Exit\n";
}
Bringing all things together in the main() function, it gives:
int main()
{
bool quit(false);
int choice, lhs, rhs;
while(!quit)
{
display_menu();
std::cin >> choice;
switch(choice)
{
case 1: ask_user_input(lhs, rhs);
std::cout << '\n' << lhs << " + " << rhs << " = " << add(lhs, rhs) << '\n';
break;
case 2: ask_user_input(lhs, rhs);
std::cout << '\n' << lhs << " - " << rhs << " = " << sub(lhs, rhs) << '\n';
break;
case 3: ask_user_input(lhs, rhs);
std::cout << '\n' << lhs << " * " << rhs << " = " << pro(lhs, rhs) << '\n';
break;
case 4: ask_user_input(lhs, rhs);
std::cout << '\n' << lhs << " / " << rhs << " = " << quo(lhs, rhs) << '\n';
break;
case 5: quit = true;
break;
default: std::cout << "Invalid choice, try again !\n";
break;
}
}
return 0;
}
Live example

How to use pointers into arrays?

So currently I am still confused in using pointers and reference and I do not know if what I am doing is right. My program is a calculator that stores everything the user inputs. There is an option that the user will be asked if he/she want to view the history and if he/she wants it the program will show all the data he/she inputs.And I need to use pointers and reference in my program but I am still confused on how to use pointers and reference into array
Here is my initialization:
int main() {
int size = 1, fNum[size], sNum[size];
char oprtn[size], answer;
;
float result[size];
int *ptrf = &fNum[size];
int *ptrs = &sNum[size];
char *ptro = &oprtn[size];
float *ptrRes = &result[size];
while (true) {
cout << "=====CALCULATOR=====\n\n";
cout << "ENTER TWO NUMBERS:" << endl;
while (!(cin >> *ptrf >> *ptrs)) {
system("cls");
cout << "INVALID INPUT. PLEASE ENTER TWO NUMBERS:\n";
cin.clear();
cin.ignore(2);
}
cout << endl;
do {
cout << "Choose Operation to be Used: \n"
<< " + --- Addition \n"
<< " - --- Subtraction \n"
<< " * --- Multiplication \n"
<< " / --- Division \n"
<< " % --- Remainder \n";
cout << "Answer: ";
cin >> answer;
cout << endl;
switch (answer) {
case '+':
cout << "ADDITION\n";
break;
case '-':
cout << "SUBTRACTION\n";
break;
case '*':
cout << "MULTIPLICATION\n";
break;
case '/':
cout << "DIVISION\n";
break;
case '%':
cout << "REMAINDER\n";
break;
default:
answer = false;
system("cls");
cout << "PLEASE ENTER A VALID ANSWER. CHOOSE BELOW.\n\n";
cout << "FIRST NUMBER: " << *ptrf << endl;
cout << "SECOND NUMBER: " << *ptrs;
cout << endl << endl;
continue;
}
} while (!answer);
cout << "DO YOU WANT TO TRY AGAIN? (Y / N): ";
cin >> answer;
switch (answer) {
case 'Y':
case 'y':
system("cls");
continue;
default:
cout << "VIEW HISTORY? (Y / N): ";
cin >> answer;
switch (answer) {
case 'Y':
case 'y':
cout << "HISTORY\n\n";
break;
default:
return 0;
}
}
}
}
This is not valid C++ code:
int size = 1, fNum[size], sNum[size]; // wrong: C++ forbids Variable Length Arrays (1)
char oprtn[size], answer; // ditto...
;
float result[size]; // ditto...
int *ptrf = &fNum[size]; // wrong: this syntax makes ptrf points one past end of array (2)
int *ptrs = &sNum[size]; // ditto...
char *ptro = &oprtn[size]; // ditto...
(1): VLA are a C language concept. Some compilers (gcc and CLang) allow it as an extension but it is useless in C++ because of the containers from the standard library
(2): the idiomatic way to initialize a pointer to the beginning of an array is just int *ptrf = Num; When used as a rvalue (in short at the right side of an = sign), an array decays to a pointer to its first element. So it reads (int *) ptr = &(fNum[0]);: ptr is a pointer to int and its initial value is the address of the first element of the array fNum
fNum[size]
is an array of one integer.
int *ptrf = &fNum[size];
Is a pointer to one past the last element of this array, therefore it's out of bounds access, this is undefined behaviour.
Since it only has one element, you declaring it as an array is pointless.
A pointer to the beginning of an array would be:
int *ptrf = fNum;
Or
int *ptrf = &fNum[0];
You can then cycle trough the array incrementing the pointer ptrf++.
To assing a pointer to a variable:
int x;
int *ptr = &x;
So the variable declarations and assignments:
int size = 1, fNum[size], sNum[size];
char oprtn[size], answer;
float result[size];
int *ptrf = &fNum[size];
int *ptrs = &sNum[size];
char *ptro = &oprtn[size];
float *ptrRes = &result[size];
Are the same as:
int fNum, sNum;
char oprtn, answer;;
float result;
int *ptrf = &fNum;
int *ptrs = &sNum;
char *ptro = &oprtn;
float *ptrRes = &result;
That said, C++ has mutch nicer data containers you can use like std::vector or std::array.
One last note, variable length arrays(fNum[size]) are forbidden in C++.

How do I send inputs from multiple functions into one function in c++?

As part of a school assignment, I need to build a modular calculator with at least four modules (getData, getInteger, processData, displayData) doing add/subtract/multiply/divide/modulus operations on two integers.
I'm getting pretty stumped on putting this thing together, and I think it's largely because I'm struggling to understand how inter-function calls work (e.g. one function sending information to another function).
I've got the getInteger function getting integer input from the user, and I'm using processdata(intA, intB); to send this to the processData(int, int) function; but my getData(int) function also needs to send an integer input to processData - however processData(select) isn't valid because it doesn't have enough arguments. (I don't really understand what this means)
This is probably a bit confusing, so I've got the whole (unfinished/wip/doesn't actually work) program here:
//calculator program
//4 modules required: getData, getInteger, processData, displayData
#include <iostream> //To input/output to the display (I think)
#include <conio.h> //For getch() at end of program
using namespace std;
//prototypes
void getInteger(int, int);
void getData(int);
void processData(int, int);
void displayData(); // haven't added anything yet
int main(){
//prevents window from immediately closing
getch();
return 0;
}
void getInteger(int, int) {
int intA, intB;
cout << "Please enter integer one: " << endl;
cin >> intA;
cout << "Please enter integer two: " << endl;
cin >> intB;
processData(intA, intB); //sends info to processData function
}
void getData(int) {
int select;
cout << "Available Functions" << endl;
cout << "1. Addition (+)" << endl;
cout << "2. Subtraction (-)" << endl;
cout << "3. Multiplication (*)" << endl;
cout << "4. Division (/)" << endl;
cout << "5. Modulus (%)" << endl;
cout << "Please type your selection (1-5): " << endl;
cin >> select;
if (select > 5 || select < 1) {
cout << "Error: Out of Bounds, please re-enter your selection: " << endl;
cin >> select;
}
processData(select); //sends info to processData function
}
void processData() {
int add, sub, mul, div, mod, select, intA, intB;
switch(select) {
case 1:
select = 1; //addition
add = (intA + intB);
displayData(add); //sends info to displayData function
break;
case 2:
select = 2; //subtraction
sub = (intA - intB);
displayData(sub);
break;
case 3:
select = 3; //multiplication
mul = (intA * int B);
displayData(mul);
break;
case 4:
select = 4; //division
div = (intA / intB);
displayData(div);
break;
case 5:
select = 5; //modulus
mod = (intA % intB);
displayData(mod);
break;
default:
cout << "There's been an error :(" << endl;
}
return 0;
}
void displayData() {
}
Am I doing this all backwards? I feel like it'd be a lot easier if I could contain this in fewer functions, but it's mandatory to keep it in (at least) 4.
Your declarations and definitions are not matching with the arguments that you are passing. i.e. void processData() is in your definition, but you declare it void processData(int, int);
The traditional approach for this problem is to collect all the data needed in some way, then call the function to do the work. For your case, you'd have to figure out the select value, and then the intA and intB values [1], then pass all three into processData.
The other opption is to chain the calls together, so ask for the select value first, then pass the select to the function that reads the data, and call the processData from there.
So you would end up with something like this:
void getInteger(int select)
{
cout << "Please enter integer one: " << endl;
cin >> intA;
cout << "Please enter integer two: " << endl;
cin >> intB;
processData(select, intA, intB);
}
void processData(int select, int intA, int intB)
{
... code goes here...
}
I'm intentionally NOT writing the complete code - the way to learn programming is to DO things for yourself. Copy-n-paste is something you probably already can do.
[1] This is a bit problematic, a function can only return one thing. Since you have two different values to return, that's not going to work. An experienced programmer would either use reference-arguments, or return a structure containing both values, but my guess is that's part of what you are learning in a future lesson, so let's skip that idea.
Here is a working version of your code... Take note of the changes and also take notice to the use of pointers in getInteger(int*,int*)
Hope this helps you out!
#include <iostream> //To input/output to the display (I think)
#include <conio.h> //For getch() at end of program
using namespace std;
//prototypes
void getInteger(int*,int*);
void getData();
void processData(int, int, int);
void displayData(int); // haven't added anything yet
int main(){
getData();
return 0;
}
void getInteger(int *ptrA, int* ptrB) {
*ptrA = 0; //safety
*ptrB = 0; //safety
int tempA = 0;
int tempB = 0;
cout << "Please enter integer one: " << endl;
cin >> tempA;
cout << "Please enter integer two: " << endl;
cin >> tempB;
*ptrA = tempA;
*ptrB = tempB;
}
void getData() {
int select = 100;
while(select != 0){
cout << "Available Functions" << endl;
cout << "0. Exit program" << endl;
cout << "1. Addition (+)" << endl;
cout << "2. Subtraction (-)" << endl;
cout << "3. Multiplication (*)" << endl;
cout << "4. Division (/)" << endl;
cout << "5. Modulus (%)" << endl;
cout << "Please type your selection (1-5): " << endl;
cin >> select;
if (select > 5 && select > 0) {
cout << "Error: Out of Bounds, please re-enter your selection: " << endl;
cin >> select;
}else if(select == 0){
break;
}
int intA, intB; //these are set in the following void
getInteger(&intA, &intB);
processData(intA, intB, select); //sends info to processData function
}
}
void processData(int intA, int intB, int select) {
int add, sub, mul, div, mod;
switch(select) {
case 1:
select = 1; //addition
add = (intA + intB);
displayData(add); //sends info to displayData function
break;
case 2:
select = 2; //subtraction
sub = (intA - intB);
displayData(sub);
break;
case 3:
select = 3; //multiplication
mul = (intA * intB);
displayData(mul);
break;
case 4:
select = 4; //division
div = (intA / intB);
displayData(div);
break;
case 5:
select = 5; //modulus
mod = (intA % intB);
displayData(mod);
break;
default:
cout << "There's been an error :(" << endl;
}
// return 0; void does not return
}
void displayData(int result){
cout << "The result is: " << result << endl;
}

Can I use a switch to hold a function?

I have a 3 file program, basically teaching myself c++. I have an issue. I made a switch to use the math function. I need and put it in a variable, but for some reason I get a zero as a result.
Also another issue, when I select 4 (divide) it crashes... Is there a reason?
Main file:
#include <iostream>
#include "math.h"
#include <string>
using namespace std;
int opersel;
int c;
int a;
int b;
string test;
int main(){
cout << "Welcome to Math-matrix v.34"<< endl;
cout << "Shall we begin?" <<endl;
//ASK USER IF THEY ARE READY TO BEGIN
string answer;
cin >> answer;
if(answer == "yes" || answer == "YES" || answer == "Yes")
{
cout << "excellent lets begin..." << endl;
cout << "please select a operator..." << endl << endl;
cout << "(1) + " << endl;
cout << "(2) - " << endl;
cout << "(3) * " << endl;
cout << "(4) / " << endl;
cin >> opersel;
switch(opersel){
case 1:
c = add(a,b);
break;
case 2:
c = sub(a,b);
break;
case 3:
c = multi(a,b);
break;
case 4:
c = divide(a,b);
break;
default:
cout << "error... retry" << endl;
}// end retry
cout << "alright, how please select first digit?" << endl;
cin >> a;
cout << "excellent... and your second?" << endl;
cin >> b;
cout << c;
cin >> test;
}else if (answer == "no" || answer == "NO" || answer == "No"){
}//GAME ENDS
}// end of int main
Here is my math.h file
#ifndef MATH_H
#define MATH_H
int add(int a, int b);
int sub(int a, int b);
int multi(int a, int b);
int divide(int a, int b);
#endif
Here is my math.cpp:
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int multi(int a, int b)
{
return a * b;
}
int divide(int a, int b)
{
return a / b;
}
}// end of int main
You're calling your functions with a and b before you get the data from the user. Try saving the math function that they selected when they enter it, and move your switch to after you have asked them for a and b.
#include <iostream>
#include "math.h"
#include <string>
using namespace std;
int opersel;
int c;
int a;
int b;
string test;
int main(){
cout << "Welcome to Math-matrix v.34"<< endl;
cout << "Shall we begin?" <<endl;
//ASK USER IF THEY ARE READY TO BEGIN
string answer;
cin >> answer;
if(answer == "yes" || answer == "YES" || answer == "Yes")
{
cout << "excellent lets begin..." << endl;
cout << "please select a operator..." << endl << endl;
cout << "(1) + " << endl;
cout << "(2) - " << endl;
cout << "(3) * " << endl;
cout << "(4) / " << endl;
cin >> opersel;
cout << "alright, how please select first digit?" << endl;
cin >> a;
cout << "excellent... and your second?" << endl;
cin >> b;
switch(opersel){
case 1:
c = add(a,b);
break;
case 2:
c = sub(a,b);
break;
case 3:
c = multi(a,b);
break;
case 4:
c = divide(a,b);
break;
default:
cout << "error... retry" << endl;
}// end retry
cout << c;
cin >> test;
}else if (answer == "no" || answer == "NO" || answer == "No"){
}//GAME ENDS
}// end of int main
It looks like you are calling your math functions (inside the switch statement) before you populate your input variables a and b. Move the cin calls to above the switch and your problems should go away.
The crash is most likely caused when you call divide(a,b) because a and b are both 0. In that case you divide by zero and the system won't be happy about that.
You are doing your calculations before you even read a and b into their variables. The cin >> statements come after your switch statements.
This is a function call:
c = add(a,b);
It assigns to c the return value of calling add with parameters a and b. At the time you're calling this function, a and b have not been initialized. Put your switch after this line:
cin >> b;
and things should work as you expect.
You need to move these:
cout << "alright, how please select first digit?" << endl;
cin >> a;
cout << "excellent... and your second?" << endl;
cin >> b;
to before the switch. If you are thinking that a function like this:
int f( int x, int y ) {
return x + y;
}
somehow returns the expression "x + y" which can be evaluated later, it doesn't. It returns the result of evaluating x + y at that point in the program. There are languages that can return an expression, but C++ isn't one of them.
c = add(a,b); within your switch statement doesn't store the function, it calls the function, passing it a and b as arguments. This is the same for all your other cases. But at that point in the program, you haven't actually set a and b yet. They are uninitialized, so they can be anything. Including 0, which would cause problems when you divide. Edit: Actually, I just realized they are globals. So they should be initialized to zero for you, which would guarantee that the divide option will fail. If a and b were local to within main, they would be uninitialized, and you could make no assumptions as to what they initially hold.
It is possible to store an address to a pointer, but its a relatively advanced topic, and I would recommend you wait until you have a better grasp on the basics before getting into it. For now, what you're better off doing is getting all your input from the user, and then processing it all at once. In pseudo-code, your loop would look something like this:
Get Operator
If Operator < 0 or Operator > 4 Then "Error"
Get A
Get B
Switch Operator
1: Result = Add(A, B)
2: Result = Subtract(A, B)
3: Result = Multiply(A, B)
4: Result = Divide(A, B)
Output result
Note that there are a lot of "gotchas" when it comes to user input. For instance, when you ask the user to input the value for a, what if they enter "Five"? At the very least, you'll want to check the status of cin after any input; this will tell you if it got any valid data from the user or not. cin.good() should tell you if the previous operation was successful, and if not you can quit, or try again, or whatever you like.
Here's an idea (using function objects or functors):
#include <iostream>
using std::cin;
using std::cout;
struct Math_Operation
{
virtual int operator()(int a, int b) = 0;
};
struct Math_Add : Math_Operation
{
int operator()(int a, int b)
{ return a + b;}
};
struct Math_Sub : Math_Operation
{
int operator()(int a, int b)
{ return a - b;}
};
struct Math_Mul : Math_Operation
{
int operator()(int a, int b)
{ return a * b;}
};
struct Math_Div : Math_Operation
{
int operator()(int a, int b)
{ return a / b;}
};
int main(void)
{
cout << "Enter operation (+, -, *, /): ";
cout.flush();
char operation;
Math_Operation * p_math_opr = NULL;
cin >> operation;
switch (operation)
{
case '+':
p_math_opr = new Math_Add;
break;
case '-':
p_math_opr = new Math_Sub;
break;
case '*':
p_math_opr = new Math_Mul;
break;
case '/':
p_math_opr = new Math_Div;
break;
default:
p_math_opr = NULL;
}
// ...Input numbers into A & B...
int A = 5;
int B = 8;
// Perform calculation with A & B
int Result = 0;
if (p_math_opr)
{
Result = (*p_math_opr)(A, B);
delete p_math_opr;
}
cout << "Result is: " << Result << "\n";
return 0;
}
The functor approach allows you to save an operation. Using pointers to base class allows you to execute the functor without knowing which operation is "in-use".
Edit:
1. Added int to function definitions in child classes.
2. Corrected execution syntax of functor.
3. Added deletion of functor.
You're calling the math functions in your switch statement before you've read a and b from the user, so it's getting called with whatever happens to be in those variables at the time. You need to move the switch after reading a and b from the user, before outputting c
This might be going overboard, but rather than using a switch to accomplish that, you can use an array of function pointers:
typedef int (*math_function)(int, int);
math_function fns[] = {NULL, add, sub, multi, divide};
cin >> opersel;
if(opersel <= 4)
cout << fns[opersel](a, b);
else
cout << "You fail :(";