Search code examples
cvariablescharcomparison-operators

How to check if variable is NOT something


Basically I want to check if char a is not 'y' or 'n'. Been trying to figure it out for an hour now and could not find anything.

#include<stdio.h>
int yesno(char a){
    do{
        printf(":");
        scanf("%s",&a);
        if((a!='y')||(a!='n')){
            printf("Incorrect awnser, try again\n");
        }
    }while((a!='y')||(a!='n'));
}
int main(){
    printf("************************************\n");
    printf("*Welcome to 'noname' 0.01          *\n");
    printf("*Do you want to start y/n?         *\n");
    printf("************************************\n");
    yesno(1);
return 0;
}

Could someone tell me how to do that? How to make it check if something is NOT something. This code is what my understanding of C allows me to create, but it's not working correctly, it just loops: Incorrect answer, try again


Solution

  • You can use continue and break statements inside the if condition.

    #include <stdio.h>
    
    int yesno(char a){
    
        do{
    
            printf(":");
            scanf("%s",&a);
            if((a=='y')||(a=='n')){
                break;
            }
            else{
                printf("Incorrect answer, try again\n");
                continue;           
            }
    
        }while((a!='y')||(a!='n'));
    }
    
    int main(){
    
        printf("************************************\n");
        printf("*Welcome to 'noname' 0.01          *\n");
        printf("*Do you want to start y/n?         *\n");
        printf("************************************\n");
        yesno(1);
    
    return 0;
    }
    

    I just changed the if condition and added the else part.