Postfix Notation Calculator - c++

I'm trying to code a postfix calculator, but I keep running into two issues-
first: When the calculator encounters a space, it sort of just exits immediately
second: when it encounters a non operator/non digit (ie- z) it doesn't display the error message that I coded.
int main()
{
stack <int> calcStack;
string exp;
char ans;
cout << "\nDo you want to use the calculator?" << endl;
cin >> ans;
while (ans == 'y')
{
cout << "\nEnter your exp" << endl;
cin >> exp;
for (int i = 0; i < exp.size(); i++)
{
if (isspace(exp[i]))
{
}
else if (isdigit(exp[i]))
{
int num = exp[i] - '0';
calcStack.push(num);
}
else
doOp(exp[i], calcStack);
}
while (!calcStack.empty())
{
calcStack.pop();
}
cout << "\nDo you want to use the calculator again?" << endl;
cin >> ans;
}
system("pause");
return 0;
}
This is the function--
void doOp(const char & e, stack <int>& myS)
{
if (myS.size() == 2)
{
int num1, num2, answ;
num2 = myS.top();
myS.pop();
num1 = myS.top();
myS.pop();
if (e == '+')
answ = num1 + num2;
else if (e == '-')
answ = num1 - num2;
else if (e == '*')
answ = num1 * num2;
else if (e == '/')
answ = num1 / num2;
else if (e == '%')
answ = num1 % num2;
else
cout << "\nError- Invalid operator" << endl;
cout << "\nCalculating..." << endl << answ << endl;
myS.push(answ);
}
else
cout << "\nInvalid stack size- too few, or too many" << endl;
}

In your main loop, you're reading strings with the string extractor:
cin >> exp;
THe string extractor is space sensitive. So as soon as a space char is encountered in the input, the string reading stops, and the witespace is not included in exp.
If you want to get a full line including spaces, you should opt for:
getline (cin, exp);
Edit:
The issue you experience with getline() is realted to the char extraction when you ask if user wants to use the calculator. Entering y is not sufficient. So you'l enter yenter. Only the y will be put into ans, so that getline() will start reading an empty line.
To solve this, update your initial input:
cin >> ans; // as before
cin.ignore (INT_MAX, '\n'); // add this to skip everything until newline included
Here an online demo showing that it works (including error message in case of wrong operator)

Related

Clearing input buffer

I am writing a program, the program is basically a guessing game. Computer displays a number and the user has to guess whether their number is higher, lower or correct. I have already made the program and its all dandy, but the only not dandy part is that I cannot figure out how to get rid of the input buffer when the user decides to play the game again. Every time the user wants to play the game, the game starts again but with the same input as the last game. I have tried putting cin.clear() in any spot I could think and also cin.clear(). But it just seems to not work. How do I clear the input?
#include <iostream>
using namespace std;
int main ()
{
int num1 = 100;
char choice;
num1 = num1 / 2;
do
{
cout << "My guess is " << num1 << ". " << "Enter 'l' if your number is lower, 'h' if it is higher, 'c' if it is correct: ";
cin >> choice;
cin.clear();
if (choice == 'h')
{
num1 = num1 + 100;
num1 = num1 / 2;
}
if (choice == 'l')
{
num1 = num1 + num1;
num1 = num1 - 11;
num1 = num1 / 2;
}
if (choice == 'c')
{
cout << "Great! Do you want to play again (y/n)?: ";
cin >> choice;
}
} while (choice != 'c' || choice == 'Y' || choice == 'y' || choice == 'n' || choice == 'N');
return 0;
}
In order to restart the game, you need to reset num1. Put the inital value in a variable that you don't change.
const int init = 100;
char choice;
int num1 = init / 2;
When the computer has guessed correctly:
if (choice == 'c')
{
num1 = init / 2; // reset
cout << "Great! Do you want to play again (y/n)?: ";
cin >> choice;
}
You could also leave the loop condition at:
} while(choice != 'N' && choice != 'n');
You should also work on the divide and conquer algorithm. For the computer to be effective, it should always make a guess in the middle of the range that is still possible, and that's not what it's doing right now. It jumps up and down, even outside the established range. An alternative could be to keep two variables to be able to shrink the possible range effectively. You could also do two separate loops, one inner loop for guessing the number and one outer that only asks the user if he/she wants to play again.
Example:
#include <iostream>
int main() {
const int initlo = 1;
const int inithi = 100;
char choice;
do {
std::cout << "Think of a number [" << initlo << "," << inithi << "]\n";
int numlo = initlo; // initialize the range
int numhi = inithi;
int guess;
do {
guess = (numlo + numhi) / 2; // guess in the middle of the range
std::cout
<< "My guess is " << guess << ". "
<< "Enter 'l' if your number is lower, 'h' if it is higher, 'c' "
"if it is correct: ";
std::cin >> choice;
if(choice == 'h') // must be in the range (guess,numhi]
numlo = guess + 1;
else if(choice == 'l') // must be in the range [numlo,guess)
numhi = guess - 1;
// exit the loop if the user cheats or the answer is correct
} while(numlo <= numhi && choice != 'c');
if(choice == 'c') std::cout << "Great! ";
else std::cout << "Cheater! ";
std::cout << "Do you want to play again (y/n)?: ";
std::cin >> choice;
} while(choice == 'Y' || choice == 'y');
std::cout << "Bye\n";
}

"Illegal else without matching if" error message c++

I am doing a programming exercise for my beginner class. The exercise is to write a c++ program that mimics a calculator.
This is the beginning of my code (not the entire code, just the beginning):
#include <iostream>
#include <string>
using namespace std;
int num1;
int num2;
double answer;
string op;
int main(void)
{
// Write your main here
cout << "Enter a number" << endl;
cin >> num1;
//Prompt user to enter an operator
cout << "Enter an operator (+, -, *, or /)" << endl;
cin >> op;
//Prompt user to enter another number
cout << "Enter another number" << endl;
cin >> num2;
//Determine whether or not addition was selected
if (op == "+")
answer = (num1 + num2);
cout << answer;
else
Regardless of what statements I put after that "else" statement, I am getting an error message that reads "Illegal else without matching if."
BUT, if I remove the preceding "cout << answer;" line, then the program compiles and runs fine.
What am I doing wrong?
Always use scope { ... } with if statements and for/while loops.
The problem is, if you don't use scope, then your if only encompasses the next statement underneath it (answer = (...). Because of this, the cout statement will happen ALL THE TIME, and the else isn't associated with the if statement. If you always use scope, you never have to worry about this.
if (op == "+") {
answer = (num1 + num2);
cout << answer;
}
You need to use {} braces on your if statement in order to execute multiple statements:
//Determine whether or not addition was selected
if (op == "+")
{
answer = (num1 + num2);
cout << answer;
}
else
...
You need to add the {} brackets between if and else because you have more than one statement.
This is what the compiler understands from your code:
if (op == "+")
answer = (num1 + num2);
cout << answer;
else
What you should do:
if (op == "+") {
answer = (num1 + num2);
cout << answer;
}
else

I am not getting a number as output but instead a emoji

enter image description hereI wrote C++ program which asks the user for two numbers and operator and gives the output based on the input.I think everything is correct but the output is not the desired output.
#include <iostream>
using namespace std;
int main()
{
int num1;
string op;
int num2;
string result;
cout << "Enter a number: ";
cin >> num1;
cout << "Enter a operator: ";
cin >> op;
cout << "Enter another number: ";
cin >> num2;
if (op == "+"){ //if user types '+' the result is num1 + num2
result = num1 + num2;
//cout << result;
}else if (op == "-"){ //if user types '-' the result is num1 - num2
result = num1 - num2;
// cout << result;
}else if (op == "*"){ //if user types '*' the result is num1 * num2
result = num1 * num2;
//cout << result;
}else if (op == "/"){ //if user types '/' the result is num1 / num2
result = num1 / num2;
//cout << result;
}else{
cout << "Invalid operator...";
}
cout << result;
return 0;
}
The output should be integer.But the output is just a diamond.
Declare the variable result as having the type int
int result = 0;
Or maybe it is even better to declare it as
long long int result = 0;
and use it like
result = static_cast<long long int>( num1 ) * num2;
In your program it has the type std::string
string result;
You are assigning a integer value to a string so I think so it is converting that integer value to character value and giving that emojis. My case was same as your, I
was assigning integer value to a string. But I then declared that integer value as a character value and it worked fine then.
Also the best approach is to use to_string() function to change the integer value to a character value.

C++ Do-while loop stopping

I got an assignment where we make a cmd prompt show up and display a flashcard game for multiplication. After inputting a correct answer a prompt shows up and asks the user to go "Again? Y/N." after the second input answer the prompt to ask the user doesn't show up and it's stuck on a "congratulations" message. This happens when I write in code to randomly generate two numbers for the game twice. one outside the while loop, and one inside while loop. If I leave one out the 2nd code for the random numbers it will run fine but will only display the same numbers over again. what I'm asking is how do I fix it so that it won't get stuck after the second answer input?
sample code below:
#include <iostream>
using namespace std;
int main()
{
int num1, num2, ans, guess, count = 0;
char choice;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//first number generator.
ans = num1 * num2;
do
{
{
cout << num1 << " X " << num2 << " = ";
cin >> guess;
cout << "Wow~! Congratulations~! ";
count++;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//second number generator.
} while (guess != ans);
cout << "\nAgain? Y/N: ";
cin >> choice;
} while ((choice == 'y') || (choice == 'Y'));
//after two turns the loop stops. Can't make a choice.
cout << " Thanks for playing! Number of tries:" << count << endl;
return 0;
}
I'd guess the problem is because your loops aren't quite what you think they are.
do
{
The code above has started a do loop.
{
I suspect you intended to start another (nested) do loop here--but you left off the do, so it's just a block that gets entered, executed, and exited. Useless and pointless in this case.
cout << num1 << " X " << num2 << " = ";
cin >> guess;
cout << "Wow~! Congratulations~! ";
count++;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//second number generator.
} while (guess != ans);
You've formatted this as if the while were closing the nested do loop--but since you didn't actually create a nested do loop, this is just a while loop with an empty body. Its meaning would be more apparent with a little re-formatting:
// second number generator
}
while (guess != ans)
/* do nothing */
;
The problem can be found here:
do
{
{
cout << num1 << " X " << num2 << " = ";
cin >> guess;
As you can see, the second scope has no do statement. As a result it is only a codeblock.
You can solve it by writing a do statement for the second code block.
Because the do is not present in the second bracket ({), the while is interpreted as a while loop:
while (guess != ans);
or
while (guess != ans) {
}
this thus keeps looping until guess is not equal to ans. But since in the loop does not modify any of the two variables, the loop will keep iterating.
Other errors: note that the program is still incorrect, since it will claim you have answered the question, regardless of the answer. You can fix it by implementing this as follows:
int main()
{
int num1, num2, ans, guess, count = 0;
char choice;
do {
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
ans = num1 * num2;
do {
cout << num1 << " X " << num2 << " = ";
cin >> guess;
if(guess == ans) {
cout << "Wow~! Congratulations~! ";
} else {
cout << "No, wrong!\n";
}
count++;
} while (guess != ans);
cout << "\nAgain? Y/N: ";
cin >> choice;
} while ((choice == 'y') || (choice == 'Y'));
//after two turns the loop stops. Can't make a choice.
cout << " Thanks for playing! Number of tries:" << count << endl;
return 0;
}

Vaildator for a string on user input

Hey i want to stop the user from entering integers when i ask the user to input a name. I have achieved this for an integer and a char. Can anyone help me adapt my code for a string.
int getNum()
{
int num;
std::cout << "\nWhat is your age? ";
while (!(std::cin >> num))
{
// reset the status of the stream
std::cin.clear();
// ignore remaining characters in the stream
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Enter an *integer*: ";
}
std::cout << "You entered: " << num << std::endl;
return num;
}
char getChar(string q)
{
char input;
do
{
cout << q.c_str() << endl;
cin >> input;
}
while(!isalpha(input));
return input;
}
string q = "This is a test123";
for(string::iterator i = q.begin(); i != q.end(); i++)
{
if((*i < 'A' || *i > 'z') && (*i != ' '))
{
return false;
}
}
would also be an option, if you allow for spaces and other characters.
Edit: updated for checking a single char:
char c;
bool finished = false;
printf("Please enter your sex, M/F?\n");
while(!finished)
{
cin >> c;
if(!(c == 'm' || c == 'M' || c== 'f' || c=='F'))
{
printf("Please try again...\n");
}
else
{
finished = true;
}
}
Note that c is only input, char by char, when Enter is pressed, before that the line feed does not happen.
If you plan on using std:string, then you can use this to find if the entered string has any digits or not:
if (std::string::npos != s.find_first_of("0123456789"))
{
std::cout << "digit(s)found!" << std::endl;
}