Homework question(boolean variables)

Here is what the question on my assignment says:
Write a do while loop that validates an input classCode. The valid inputs are 'F','S','J', or 'R'. Use a Boolean variable invalid to assign the invalid expression.

Type this into Eclipse and run test cases to demonstrate that it works properly (be sure to test all of the valid input value and some invalid input values).

Have it output the input and either "is an INVALID INPUT- Please try again!" or "is valid - thank you!"
(e.g. G is an INVALID INPUT - please try again! OR F is valid - thank you!)

Any help is greatly appreciated

char classCode;
bool invalid;

invalid = classCode !=('F' || 'S' || 'J' || 'R'); /* I think this line is the problem, it doesn't cause a compile time error but only outputs "error" no matter what is input. */

do
{
cout << "enter a number ";
cin.get(classCode);
cin.ignore(10000, '\n');


if(invalid)
{
cout << "error" << endl;
}
}while(invalid);
cout << "good value";
Note that = in C++ is assignment. It means assign the value on the right to the variable on the left. It will not automatically change the variable's value when the the variables used on the right changes later in the program.

In your program the invalid variable is set once before the loop, so the value never change inside the loop. You probably want to put that line somewhere inside the loop instead.

|| is an operator that takes two arguments. If both arguments are false it will return false, otherwise it returns true. When using integer (or char) instead of a bool value (true/false), zero will be treated as false and everything else as true. None or 'F', 'S', 'J' , 'R' is 0 so the line will be evaluated like this:
1
2
3
4
5
6
invalid = classCode !=((('F' || 'S') || 'J') || 'R');
invalid = classCode != (((true || true) || true) || true);
invalid = classCode != ((true || true) || true);
invalid = classCode != (true || true);
invalid = classCode != true;
invalid = classCode != 1

You don't need to fully understand what is going on here. The important thing to realize is that || usually doesn't make sense on other things than bool values. So what you really want to do is check if classCode is not equal, for each character:
 
invalid = (classCode != 'F' || classCode != 'S' || classCode != 'J' || classCode != 'R');
Last edited on
Topic archived. No new replies allowed.