if (userChoice == 0)
cout << 0;
if (userChoice == 1)
cout << 1;
else
cout << -1;
However, when I input a string like "hfg", then the output is 0-1. This means that the first condition was met, and the last condition was met. But how!? Shouldn't the output just be -1?
and enter invalid data (such as "hfg" or signal end of input), userChoice will get filled with the value 0, and the cin stream will be set into a state of failure.
(Note: Pre-C++11, whatever the value that was in userChoice before the cin >> call would remain as-is, meaning in your case it would be uninitialized.)
So, if userChoice is now 0, then your first if-statement logic will print 0.
Next, you have it checking if userChoice == 1. It isn't, so it prints -1. 0-1
The better way to check for invalid input (e.g. entering a string into an int) is to check the state of the cin stream
1 2 3 4 5 6 7 8 9
int userChoice;
if (cin >> userChoice)
{
cout << "Success\n";
}
else
{
cout << "Invalid input\n";
}