Here's the problem: I've made a simple calculator following instructions from learncpp.com. However, after putting in the operator, the program goes bananas.
This is what I was expecting:
Please enter a number: 1
Please enter an operator: +
Please enter another number: 2
Your result is: 3
However, after hitting Enter on entering the operator (in this example, +), this happened:
Please enter a number: 1
Please enter an operator: +
Please enter another number: Your result is: 0
#include <iostream>
#include <string>
usingnamespace std;
int GetUserInput1()
{
cout << "Please enter a number: ";
int userInput;
cin >> userInput;
return userInput;
}
int GetUserOperator()
{
cout << "Please enter an operator: ";
int theoperator;
cin >> theoperator;
return theoperator;
}
int GetUserInput2()
{
cout << "Please enter another number: ";
int userInputTwo;
cin >> userInputTwo;
return userInputTwo;
}
int CalculateResult(int FirstInput, int TheOperator, int SecondResult)
{
if (TheOperator=='+')
return FirstInput + SecondResult;
if (TheOperator=='-')
return FirstInput - SecondResult;
if (TheOperator=='*')
return FirstInput * SecondResult;
if (TheOperator=='/')
return FirstInput / SecondResult;
return 0;
}
void PrintResult(int TheResult)
{
cout << "Your result is: " << TheResult << endl;
}
int main()
{
// First input
int Input1 = GetUserInput1();
// Operator
int Operator = GetUserOperator();
// Second Input
int Input2 = GetUserInput2();
// Go calculate or something
int TheResult = CalculateResult(Input1, Operator, Input2);
// Print the result
PrintResult(TheResult);
return 0;
}
Yes, you're casting a character that the user inputs into an int. There isn't really much wrong with it, but it's hard to exactly tell how iostream will handle the cast. I simply switched the operator function and variable to char and it worked fine.
Operator is a character, but you try to read it into an integer.
That read statement will fail, which sets the cin.fail() flag, and the rest of the input will also fail.