Why does an integer prompt accept strings?

closed account (Ey80oG1T)
I have this code...

int userChoice;
cin >> userChoice;

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?

What's happening here? Thanks
When you do
1
2
int userChoice;
cin >> userChoice;

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";
}


See also: https://stackoverflow.com/a/39282970/8690169
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main() {
    int n = 0;
    while (std::cout << "Enter n: ", !(std::cin >> n))
    {
        std::cout << "Bad input\n";
        std::cin.clear();
        std::cin.ignore(1000, '\n');
    }
    std::cout << "n: " << n << '\n';
}

1
2
3
4
5
6
if (userChoice == 0)
cout << 0;
if (userChoice == 1)
cout << 1;
else
cout << -1;

is same as
1
2
3
4
5
6
7
8
9
10
11
if (userChoice == 0) {
  cout << 0;
} // first if statement ends here


if (userChoice == 1) {
  cout << 1;
}
else {
  cout << -1;
} // second if ends here 

Did you mean:
1
2
3
4
5
6
7
8
9
if (userChoice == 0) {
  cout << 0;
}
else if (userChoice == 1) {
  cout << 1;
}
else {
  cout << -1;
} // first if ends here 

closed account (Ey80oG1T)
keskiverto

I do realize that, but in this context, when the if statements are grouped together, don't they act the same as if else statements?
Whitespace doesn't matter.

1
2
3
4
5
6
if (a)



    part_of_if_statement();
    NOT_part_of_if_statement();

is clearer when formatted as:
1
2
3
if (a)
    part_of_if_statement();
NOT_part_of_if_statement();


1
2
3
4
5
if (a) {
    part_of_if_statement();
    STILL_part_of_if_statement();
}
    NOT_part_of_if_statement();

Not sure if that answers your concern.
Last edited on
Topic archived. No new replies allowed.