Home > front end >  The output does not match with the input (C language)
The output does not match with the input (C language)

Time:09-29

I am making a simple C program that would ask your age and gender. If your gender is not M or F the program will ask for a different input. If your age is less than zero, the program will require for another input. This is my code:

#include<stdio.h>

int main(){
    
    int a;
    char g;
    
    entry:
    printf("%s","AGE : ");
    scanf("%d", &a);
    getchar();
    
    insert:    
    printf("%s","GENDER :");
    scanf("%s", &g);
    getchar(); 
    
    while (a < 0){
        goto entry;
        }
    
    switch(g){
        
        case 'M':{
            printf("I am a %d yr old male", a);break;
        }
        case 'F':{
            printf("I am a %d yr old female", a);break;
        }
        default:{
            goto insert; break;
        }
    }

    return 0;
}

and this is an example of the program running

AGE : 21

GENDER :M

I am a 0 yr old male

CodePudding user response:

Altough I detected a weirdness (see the large comment) in code, it outputs as you expected so you can use an approach like this:

#include<stdio.h>
#include<stdbool.h>

int main(){

    int age, a;
    char g;
    bool validInput;

    do {
        validInput = true;

        printf("%s","AGE : ");
        scanf("%d", &age);
        /*
         * If you use directly the 'a' var, somehow it will not print
         * input age. That's why I had to use a = age assignment.
         * This is weird, if someone knows why this happens let me
         * know please.
         */
        a = age;
        if(a < 0) {
            validInput = false;
        }

        printf("%s","GENDER : ");
        scanf("%c", &g);
        getchar();
        if(g != 'M' && g != 'F') {
            validInput &= false;
        }

    } while(!validInput);

    switch(g){

        case 'M':
            printf("I am a %d yr old male\n", a); break;
        case 'F':
            printf("I am a %d yr old female\n", a); break;
        default:
            printf("Oops! Something went wrong...\n");
    }

    return 0;
}
  • Related