Home > Enterprise >  Why isn’t my input-based if statements working in C?
Why isn’t my input-based if statements working in C?

Time:11-13

For some reason, my code isn’t working in C.

Please check the code below:

#include <stdio.h>
#include <string.h>
int main(){
while (1){
printf(“Is Python a programming language? “);
char question[4];
scanf(“%s”, &question);

if (strcmp(question, “yes”) == 0 || (strcmp(question, “YES”) == 0 || (strcmp(question, “Yes”) == 0 ))){ //the reason why I’m using so many “or” statements is because idk how to lowercase the input (pls help me if you can)
printf(“Correct”);
} else {
printf(“Incorrect”);
continue;
}
}

CodePudding user response:

  1. Your OR in if does not cover all possible permutations. It can be also yEs od yeS etc etc.
char *strtouppper(char *str)
{
    char *wrk = str;
    while(*wrk) {*wrk = toupper((unsigned char)*wrk); wrk  ;}
    return str;
}

int main(void)
{
    char answer[4];

    while (1)
    {
        printf("Is Python a programming language? ");
        if(scanf(" %3s", answer) != 1) {printf("\n\nInput error");break;};

        if(!strcmp("YES", strtouppper(answer)))
            printf("\nCorrect\n");
        else 
            printf("\nIncorrect\n");
    }
}

https://godbolt.org/z/vahd9be9M

CodePudding user response:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
char * low(char * str){//a function for solve lowercase and uppercase and mix
 for(int i = 0; str[i]; i  ){
    str[i] = tolower(str[i]);
 }
}
int main(){
while (1){
    printf("Is Python a programming language? ");
    printf("\n");
    char question[4];
    scanf("%s", question);
    low(question);
    if (strcmp(question, "yes") == 0 ){ 
    printf("\nCorrect");
    break;} 
    else {
    printf("\nIncorrect");
    continue;}
 }
}
  • Related