comparing chars in a while statement

Jul 1, 2014 at 10:47am
Hi there, im trying to do this but it can never seem to work.

#include <iostream>
using namespace std;

int main ()
{

char charOne;

cin.get(charOne);
cin.ignore(1000, '\n');

while( gender != 'a' || gender != 'A')
{
cout << "Hello World";

cin.get(charOne);
cin.ignore(1000, '\n');
}

return 0;
}

basically i want to keep looping until i enter an a or A (also does this apply to if statements aswell?) no idea what im doing wrong, any help will be greatly appreciated
Last edited on Jul 1, 2014 at 11:00am
Jul 1, 2014 at 11:09am
Please use code tags, to make your code readable:

http://www.cplusplus.com/articles/z13hAqkS/

Regarding your question, the problem lies with the logic of your while loop. Look at the condition:

gender != 'a' || gender != 'A'

Can you tell us under what circumstances that can ever be false?
Last edited on Jul 1, 2014 at 11:09am
Jul 1, 2014 at 11:11am
Your code does not compile. The name gender is undefined.

Also, the logical or operator || should be changed to a logical and &&.
If the character is 'a', it cannot simultaneously be 'A', thus one of the not-equal tests will always be true. When || is used, that means the condition as a whole is always true.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main ()
{
    char charOne;
    
    cin.get(charOne);
    cin.ignore(1000, '\n');
    
    while( charOne != 'a' && charOne != 'A')
    {
        cout << "Hello World";
        
        cin.get(charOne);
        cin.ignore(1000, '\n');
    }
    
    return 0;
}
Jul 1, 2014 at 11:16am
Thanks guys but i figured it out like 10 seconds ago, had to read my notes on the boolean operators. That being said ill make sure to use code tags, sorry about the mistake first time on the boards.
Jul 1, 2014 at 11:28am
No problem - glad it worked out! Welcome to the boards :)
Jul 1, 2014 at 11:34am
out of curiosity can i use boolean operators to compare c-strings aswell? or do i have to figure out a way to put string compare in them?
Jul 1, 2014 at 11:46am
It's simpler (and generally better) to use std::string.

But if you do find you have to use c-string, then use strcmp() to compare. That returns zero when strings are equal.


http://www.cplusplus.com/reference/cstring/strcmp/
Topic archived. No new replies allowed.