!= not working

Im trying to check a variable to make sure it equals a certain character but it is not working

cout << "Which package are you shopping for? (enter B, S, D)?" << endl;
cin >> userResponse;

if (userResponse != 'b','B','s','S','d','D'){
cout << "This is not a valid answer, try again" << endl;
}

I get an the message whether it has the terms or not
(userResponse != 'b' && userResponse != 'B' && userResponse != 's' && userResponsie != 'S' && userResponse != 'd' && userResponsde != 'D')

But also you could do:

(tolower(userResponse) != 'b' && tolower(userResponse) != 's' && tolower(userResponse) != 'd')
tolower() is a function from #include<cctype>
!= doesn't compare against lists of things.

You need to compare against each one, like say
1
2
3
if ( userResponse != 'b' && userResponse != 'B' ) { // add more && as needed
    cout << "This is not a valid answer, try again" << endl;
}


You can halve the number of tests by converting case to begin
1
2
3
4
userResponse = toupper(userResponse)
if ( userResponse != 'B' ) { // add more &&, with just the capitals.
    cout << "This is not a valid answer, try again" << endl;
}


Or create a search string
1
2
3
if ( string("BSDbsd").find(userResponse) == std::string::npos ) {
    cout << "This is not a valid answer, try again" << endl;
}

http://www.cplusplus.com/reference/string/string/find/



Thank you two, that helped a lot.
See "Comma operator" and "operator precedence" in: http://www.cplusplus.com/doc/tutorial/operators/

1
2
3
4
5
6
7
if ( A != B, C, D )
// is thus same as
if ( (A != B), C, D )
// and equivalent to
A != B;
C;
if ( D )
Topic archived. No new replies allowed.