my code does not work and I don’t know why ;-;

Since you wish to expect a ‘w’ to be inputted (among ‘w’, ‘a’, ‘s’, ‘d’ as probable movement characters ) , which actually is a character hence you must specify %c as an argument to the scanf function.

So, your code should look like

#include <stdio.h>

int main () {
int x = 0;
int y = 0;
int z = 0;
char input;

scanf("%c", &input);

if( input == 'w' ) {

    printf("test");
    y++;

    }
}

Understand that “Hello” is a string composed of individual characters ‘H’, ‘e’, ‘l, ‘l’, ‘o’.

Therefore , if you had just wanted to input, say a ‘H’, which is a character , you would say that to scanf by passing “%c” as an argument , and , if you had wanted to store “Hello”, which is a string of individual characters , then you would have passed “%s” into your scanf.

Moreover , Segmentation faults occur when you try to store/retrieve data into a memory that does not exist or into an invalid/unauthorised location. IN your case you are trying to store a string into a variable meant to store a character.Hence the warning.

The warning also mentions the char variable ‘input’ as an int because characters are essentially represented by thier ASCII values which are integers, i.e, ‘A’ has value 65, ‘B’ has 66 and so on.

A more complete code for you would look like:

#include <stdio.h>

int main () {
int x = 0;
int y = 0;
int z = 0;
char input;

scanf("%c", &input);

if( input == 'w' ) {

    printf("test");
    y++;

    }else if( input == 's'){

      x++;

    }else if( input == 'a'){

        z++

    }else{

        printf("\nSorry ! unrecognised input !\n");

    }
}

Albeit , a more better design would be :

#include <stdio.h>

int main () {
int x = 0;
int y = 0;
int z = 0;
char input;

scanf("%c", &input);

    switch(input){

            case 'w':
                    printf("test");
                    y++;
                    break;

            case 's':
                    x++;
                    break;

            case 'a':
                    z++;
                    break;

            default:
                    printf("\n Sorry ! invalid input\n");


    }

}

Leave a Comment