Reputation: 15
I've got this very simple code. Just an if statement with three outcomes between 1, 2, and everything else. The desired behavior is that after outputting the appropriate response, the program will wait for the user to hit the enter key before closing. But if a string is entered, cin seems to fail despite the fact it doesn't fail for a single character. Why is that?
Also, if I enter a 30 digit number, the program will output "nope" as it should, but the user will need to hit enter twice before it closes. How come?
Also, I'm not exactly looking for a solution to the problem, just an understanding as to why these things happen.
#include <iostream>
int main()
{
int choice;
std::cout<< "1 or 2?"<< std::endl;
std::cin>> choice;
if (choice == 1)
{
std::cout<< "boom"<< std::endl;
}
else if (choice ==2)
{
std::cout<< "bam"<< std::endl;
}
else
{
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore();
std::cout<< "nope"<< std::endl;
}
else if (choice != 1 || 2)
{
std::cout<< "nope"<< std::endl;
}
}
std::cin.ignore();
std::cin.get();
return 0;
}
Thank you for your time and I apologize if this question is overly simple. I just had no idea how to phrase it for Google.
Upvotes: 1
Views: 103
Reputation: 3245
and the reason why you are having to hit enter twice before it closes when you enter any number larger thatn 10 digits is because you have an extra
std::cin.ignore();
after the last else statement.
so basically when it goes past the 10th digit it will ignore what ever is next and then wait for the user to hit enter (or any key) again. then it will close out.
I could be wrong.. but I think thats the reason why..
int has a limit on how big it can get..
Upvotes: 0
Reputation: 2646
else if (choice != 1 || 2)
This line of code is not doing what you suspect
You have to actually write the code below
else if (choice != 1 || choice != 2)
This is subtle because of the way we speak English. Your code would say "else if choice is not equal to 1 or 2... Seems to make logical sense, but if you really think about it...what are you comparing two with. We know we are comparing one with choice, but what about two?
The code I showed says more accurately and precisely, "else if choice is not equal to one or choice is not equal to two" Now we know that on both sides of the or, we are comparing the integer values of 1 and 2 with choice
NOTE: The else if here is actually entirely useless because you know from the original if and else if and else that the choice is not a one or two. The fact that you are in that else block already tells you that choice is not a one or two, So you really don't need this redundancy of logic here.
Upvotes: 2
Reputation: 3245
i always used #include <conio.h>
and right before return 0
, i do
_getch();
also in ur code where u have else if (choice !=1|| 2)
, it should be
else if (choice !=1 || choice !=2)
Upvotes: 0