What I want it to do is: if input doesn't fail, then it will go to else statement, and then input_is_good will be assigned to true. Thus, I can go to the next if statement if input is correct, otherwise don't execute the second id statement. But when I compile the program, it says input_is_good is undeclared (first use this function) But I do declare it in the else statement.
I also try the following way:
if ( cin.fail() )
{............}
else { int input_is_good = '1' ; } //btw do I need to single quote 1??
You're defining the variable in a different (inner) scope, and so C++ (the compiler) doesn't know about it anymore after you pass by the closing brace }, (i.e. the end of the block.)
1 2 3 4 5 6 7 8 9 10 11 12
int input_is_good = false; //defined in this scope; use true/false in C++ (not 1/0)
if( cin.fail() ) {
...
} else {
...
input_is_good = true; //fine, this block is nested inside so it can still see input_is_false
}
if( input_is_good ) {
...
}
That being said, there are better ways to accomplish this. For example, why don't you put the "if input_is_bad" code directly in the else block (my line 6)?
btw do I need to single quote 1?
No. 1 without quotes is an int literal: i.e. 0000 ... 0001 = 110
'1' with quotes is a char literal: i.e. 0011 0001 = 4910