• 0

Newb w/ C++ Nested If Statement Question


Question

Hello all,

I'm not looking for an exact answer, but hopefully just a nudge in the correct direction. The following code compiles fine, but when I execute it and enter a valid value (i.e. A, B, C), it always prints "Incorrect grade, please enter a valid grade" on the screen. The number of grades tallies up just fine however. Am I using an incorrect operator somewhere in my nested If statement? Is my nested if statement even correct? I know that once I figure out what is wrong, I'll wonder how I overlooked it. Any help that you could offer would be much appreciated. Thank you for your time.

- Mike


#include<stdio.h>
/*function main begins program execution*/
int main()
{

int grade = 0; /*one grade*/
int aCount = 0;/*number of A's*/
int bCount = 0;/*number of B's*/
int cCount = 0;/*number of C's*/
int dCount = 0;/*number of D's*/
int fCount = 0;/*number of F's*/

printf("Enter the letter grades.\n");
printf("Enter the EOF character to end input which is ctrl z.\n\n");


   while ( (grade = getchar() ) != EOF) {
     if ( grade  == 'A' || grade == 'a' )
	aCount++; 
     else if ( grade == 'B' || grade == 'b')
        bCount++;
     else if (grade == 'C' || grade == 'c')
	cCount++;
     else if (grade == 'D' || grade == 'd')
        dCount++;
     else if (grade == 'F' || grade == 'f')
        fCount++;
     else
        printf("Incorrect grade, please enter a valid grade.\n");
} /*end while*/

printf("A: %d\n", aCount);
printf("B: %d\n", bCount);
printf("C: %d\n", cCount);
printf("D: %d\n", dCount);
printf("F: %d\n", fCount);


}/*end main*/

5 answers to this question

Recommended Posts

  • 0

There is nothing wrong with your if statements. What is happening is that when you enter (for example) "a" and press return, both of these keys are stored in the input buffer. Your loop runs through once with grade set to 'a', then it runs through again with grade set to '\n' (the newline character), which is where the "invalid grade" is coming from. So, to fix this particular problem, you could make your "invalid grade" message print if grade isn't the '\n' character.

Edited by David Scaife
  • 0
There is nothing wrong with your if statements. What is happening is that when you enter (for example) "a" and press return, both of these keys are stored in the input buffer. Your loop runs through once with grade set to 'a', then it runs through again with grade set to '\n' (the newline character), which is where the "invalid grade" is coming from. So, to fix this particular problem, you could make your "invalid grade" message print if grade isn't the '\n' character.

That's exactly it.

You could do it this way, by adding in another else if

else if ( grade == '\n' ) 
 continue;

The continue statement jumps to the while statement.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.