Daniel Samuel Daniel Samuel - 8 days ago 9
C Question

Keyboard input and different keys having different response

The code below is suppose to get a keyboard input from the user that is either W,A,S or D. When each key is pressed a different message is needed to appear on screen. I am suppose to use an if statement to complete this task. At the moment, the wrong responses are appearing with the wrong inputs.

The current results I get are:


  1. Input W = Character going UP and Character going RIGHT

  2. Input S = Character going DOWN and Character going RIGHT

  3. Input A = Character going LEFT and Character going RIGHT

  4. Input D = Character going RIGHT



The results I want are the following:


  1. Input W = Character going UP

  2. Input S = Character going DOWN

  3. Input A = Character going LEFT

  4. Input D = Character going RIGHT



Thank You

#include <stdio.h>

int main()
{
char keyInput[2];
//Instructions for user to follow
printf("Controls: \n");
printf("W = UP: \n");
printf("A = LEFT \n");
printf("S = DOWN \n");
printf("D = RIGHT \n");
printf("\nWhich direction do you want to go?");

scanf("%s", keyInput);

//choices
if (*keyInput == 'W')
{
printf("Character going UP\n");
}
else if (*keyInput == 'A')
{
printf("Character going LEFT\n");
}
else if (*keyInput == 'S')
{
printf("Character going DOWN\n");
}
else if (*keyInput == 'D');
{
printf("Character going RIGHT\n");
}
return 0;
}

Answer

This line:

else if (*keyInput == 'D');

should NOT end in a semi-colon