So I just started self-teaching C++ yesterday and I'm already stuck. It's terrific learning it so far and has been a blast, but now I'm at a roadblock and finding a solution has been impossible for me. Merely trying to make a simple password checking program that can compare multiple codes with one if statement. I'm thinking it's the "moorian or" in the cin line? Commenting out the "b" parts still caus it to run the same, otherwise b doesn't execute properly (though it still builds and doesn't error out). I'm at a loss
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
int a;
int b;
cout <<"Please enter your password."<<endl;
cin >> b >> a;
if (a == 123456 || b == 654321)
{
cout <<"I win.";
}
}
Thank you. Now it's the closest to being 100% than I've been able to achieve. However it requires two entries for it to confirm either of the passwords or the fail.
To extend Peter87's answer, the >> is an operator ( just like + ) that takes an istream ( cin ) on the left and some type on the right. The >> operator returns the istream, which is why you are able to chain >> like you have done in the edit.
The || operator returns true if the value on its left is true, otherwise it returns the value on its right. An istream is convertable to boolean ( so something like if ( cin >> b ) is valid, valuable as well ).
So, cin >> b || a; is perfectly valid code. It extracts b from standard input, checks to see if the istream is in a "good" state, and if not, converts "a" to boolean. Maybe this makes what is happening more clear: bool value = cin >> b || a;
Or even more clear:
1 2 3 4 5 6
cin >> b;
bool value = cin || a;
// or
cin >> b;
bool value = cin.good() || a;
My initial wording may have been too ambiguous; my apologies, I would like for either of the passwords to work.
Edit; I could be going about this the entirely wrong way, it's just the book I'm using didn't really explain how to do this, but it was a challenge at the end of the chapter and now I must figure out how to do it
wow thank you all, I see the error in my ways. No! such a simple solution, that's way I'm loving coding so much, even simple coding.
Again thank you all for the help, truly appreciative