if else question

Hi, The problem is When I type in G It displays Grade , I want it to display not grade! , infact no matter what number I type in it always displays Grade , Please help thanks!


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


int main() {
char Grade;
cin >> Grade;

    if (Grade == 'A'||'B'||'C'||'D'||'E'||'F')
        cout << "Grade";
       else if ( Grade =='G')
        cout <<"Not Grade";
    
    
    return 0;
}


UPDATE okay so I tried this and it worked but is their a way to make it simpler?? thanks

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


int main() {
char Grade;
cin >> Grade;

    if (Grade == 'A'|| Grade == 'B'|| Grade =='C' || Grade== 'D'|| Grade == 'E' || Grade =='F'||Grade == 'a'|| Grade == 'b'|| Grade =='c' || Grade== 'd'|| Grade == 'e' || Grade =='f') 
        cout << "Grade";
       else if ( Grade =='G'|| Grade == 'g')
        cout <<"Not Grade";
    
    
    return 0;
}
Last edited on
C++ does not support implied left hand side in conditionals. You must fully specify the conditions.
Example:
if (ans == 'Y' || 'y') evaluates as if ((ans == 'Y') || ('y'))

('y') always evaluates to 1 (true), therefore the if statement is always true.

s their a way to make it simpler??

Try upshifting Grade before you test it. That cuts the number of comparisons in half.
 
Grade = toupper(Grade);

You could also try a switch statement.
1
2
3
4
5
6
7
8
9
10
11
12
switch (Grade)
{
case 'A':    // Note:  No break statements.
case 'B':    // Just fall through.
case 'C':
case 'D':
case 'E':  
case 'F': cout << "Grade";
             break;
case 'G': cout << "Not Grade";
              break;
}
Last edited on
Or you could try:
1
2
if (std::toupper (Grade) == 'A') || std::toupper (Grade) == 'B' || /* ... */ )
{ /*...*/}


That's still a bit long though. But it doesn't modify the Grade variable, which may or may not be necessary– I prefer to only change my variables if I need to so I'd do it this way, especially if you're going to be using Grade somewhere else.

For the switch statement:
1
2
3
4
5
6
upGrade = std::toupper (Grade);

switch (upGrade)
{
     /* the stuff that AbstractAnon suggested which is a great idea */
}

That way it doesn't alter the Grade variable.

That being said, it doesn't matter as mch if you aren't going to use Grade anywhere else, but I would err on the side of caution, just in case.

Good luck!
max
okay so I tried this and it worked but is their a way to make it simpler??
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;


int main() {
char Grade;
cin >> Grade;

Grade = toupper(Grade);

    if ((Grade >= 'A') && (Grade <= 'F'))
        cout << "Grade";
       else if ( Grade =='G')
        cout <<"Not Grade";
    
    
    return 0;
}
 
if (strchr("abcdef", tolower(Grade)))
Topic archived. No new replies allowed.