Why is my boolean function not working

Hi,

Been stuck on this program for a long while now and can't get the boolean function to work, it keeps on returning false when it is true.
#include <iostream>
using namespace std;

int main()
{
bool inputGood = false;
string message;
int i = 0;
while (!inputGood)
{
cout << "Please enter a message CONTAINING only letters and spaces" << endl;
getline(cin, message);
for(i = 0; i < message.size();i++)
{
if(message[i] > 122 || message[i] < 97 || message[i] != 32)
{
inputGood = false;
cout << "Input bad";
return false;
}
else
{
inputGood = true;
cout << "Input good";
return true;
}
}
}
return 0;
}
Think about your line if(message[i] > 122 || message[i] < 97 || message[i] != 32). You might need a mix of ANDs and ORs.

Your statement say, if the character is > 122 OR the character is < 97 OR the character is NOT 32, then inputGood is false. Well, there are no values that don't satisfy these conditions. According to the first 2 conditions, only value >= 97 and <= 122 will be considered to make inputGood = true. But your third condition says that anything that is not 32 will make inputGood = false. Thus inputGood will always be false.

What you want to do is allow 32 and any value between 97 and 122 (inclusive) to be accepted. You can't do that with only ORs (well you can, but it becomes very ugly with a handful of NOTs sprinkled in). Pull out your handy dandy && operator and create the condition you want. You probably want parentheses () too.
You're function only checks for lowercase letters, and thus will print "input bad" when a capital letter is entered. Aside from that, the program also prints "input bad" as soon as it see's a character that is not a space. Thus even entering only letters will cause the program to execute the if-clause.

You should change your if-condition to checking for letters and spaces, and the else is then executed when its NOT letters or spaces.

Also, you cannot return a boolean within the main function. You need to write this code in a separate function and return bool from there.
Last edited on
With or conditions, there is short circuiting: as soon as one of the conditions is true, then the others are not evaluated. This makes sense logically, if any one of them is true then the whole thing is true.

It might be easier to evaluate when inputGood should be true, rather than the other way around.
Topic archived. No new replies allowed.