Home > Software design >  if statement unable to check the value
if statement unable to check the value

Time:09-29

can someone tell me what's wrong with this code. The value is being stored in 'ch' but if statement is unable to validate it.

scanf(" %c", &ch);
            if (ch == 4){
                    printf("Correct Answer \n");
                    score  ;
            }
            else{
                    printf("Wrong Answer \n");
            }

CodePudding user response:

%c means you are expecting a character. So a 4 you input, is not an integer 4, but a character '4'.

Simply check for ch == '4'

CodePudding user response:

Note that char is a numeric type, so this will compile and run, but not do what's expected because we've read a char (with format specifier %c into a char variable ch, but then compare it to the number 4 rather than the character '4'.

You should also get in the habit of checking the return value of scanf as a failure to read into ch if it's uninitialized will lead to unexpected behavior.

if (scanf(" %c", &ch) != 1) {
    // Something to handle the error.
}

if (ch == '4') {
    printf("Correct Answer \n");
    score  ;
}
else {
    printf("Wrong Answer \n");
}
  •  Tags:  
  • c
  • Related