Reputation: 327
I'm trying to learn some C++, and I decided to build a basic I/O calculator. It runs correctly until the second getUserInput(), then it automatically inputs 0 and terminates. I can't figure out what is happening!
#include <iostream>
using namespace std;
int getUserInput() { // Get user numbers
cout << "Enter a number: " << endl;
int userInputNumber;
cin >> userInputNumber;
return userInputNumber;
}
char getUserOper() { // Get user math operator
cout << "Enter a math operator: " << endl;
int userInputOper;
cin >> userInputOper;
return userInputOper;
}
int doMath(int x, char oper, int y) { // Does math based on provided operator
if(oper=='+') {
return x + y;
}
if(oper=='-') {
return x - y;
}
if(oper=='*') {
return x * y;
}
if(oper=='/') {
return x / y;
}
else {
return 0;
}
}
void printResult(int endResult) { // Prints end result
cout << endResult;
}
int main() {
int userInputOne = getUserInput();
char userOper = getUserOper();
int userInputTwo = getUserInput();
printResult(doMath(userInputOne, userOper, userInputTwo) );
}
Upvotes: 2
Views: 530
Reputation: 5313
when you do cin >> userInputOper the \n is still in the buffer and then gets used the second time. Causing invalid input to exist and undefined behavior. So do
cin >> userInputOper;
//cin.ignore(); // removes one char from the buffer in this case the '\n' from when you hit the enter key, however " " is a delimiter so if the user enters 23 54 only 23 gets entered and 54 remains in the buffer as well as the '\n' which will get used on the next call
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); // clears everything in the buffer
return userInputOper;
Also you should be checking for errors on input
int myInt;
while ( !(cin >> myInt) )
{
cout << "Bad input try again\n";
cin.clear(); // this only clears the fail state of the stream, doesn't remove any characters
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); // removes all chars from the buffer up to the '\n'
}
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
You should probably take in a char for the operator though not entirely necessary. You will run into problems when the user inputs a number larger than a char 255.
Upvotes: 1
Reputation: 16364
char getUserOper() { // Get user math operator
cout << "Enter a math operator: " << endl;
char userInputOper;
cin >> userInputOper;
return userInputOper;
}
You need to use a char instead of int.
Upvotes: 1
Reputation: 9863
Your using int when you should be using a char in getUserOper
char getUserOper() { // Get user math operator
cout << "Enter a math operator: " << endl;
char userInputOper;
cin >> userInputOper;
return userInputOper;
}
Upvotes: 3
Reputation: 3870
Use a char
in getUserOper
char getUserOper() { // Get user math operator
cout << "Enter a math operator: " << endl;
char userInputOper;
cin >> userInputOper;
return userInputOper;
}
Upvotes: 1