-2

I ask the user to enter a letter and each letter does something different. If they enter anything else it prints out the else statement at the end. The problem is that the else statement is printed no matter what I enter and it prints "Enter a letter: " twice. I've been searching google and stack overflow, and I don't know if I'm blind or what but I can't find the answer. Please help.

    while(false){ //I have a method here that returns true or false
    printf("Enter a letter: ");
    char letter;
    scanf("%c", &letter);

    if(letter == 'a'){ //position left
        //do some code
    }else if(letter == 'd'){ //position right
        //do some code
    }else if(letter == 'w'){ //value up
        //do some code
    }else if(letter == 'x'){ //value down
        //do some code
    }else{
        printf("NEW MOVEMENT: Enter a valid command by keyword:\n");
        printf("Valid commands: a d w x\n");
    }
}
Anonymous
  • 57
  • 1
  • 9

2 Answers2

2

I think your problem is the left out newline character \n after scanf()

Change the scanf() code to

scanf(" %c", &letter);

The space before the %c should escape the left out newline \n character.

Haris
  • 12,120
  • 6
  • 43
  • 70
0

if you write while(false),the body of the loop will not be executed.you need to write while(true) instead.Also,when you use scanf you have to watch out for the '\n' character,as that will have effect on the output.The added space to the scanf statement before %c should deal with that.

 while(true){
    printf("Enter a letter: ");
    char letter;
    scanf(" %c", &letter);

    if(letter == 'a'){ //position left
        //do some code
    }else if(letter == 'd'){ //position right
        //do some code
    }else if(letter == 'w'){ //value up
        //do some code
    }else if(letter == 'x'){ //value down
        //do some code
    }else{
        printf("NEW MOVEMENT: Enter a valid command by keyword:\n");
        printf("Valid commands: a d w x\n");
    }
}
machine_1
  • 4,266
  • 2
  • 21
  • 42