Basel Eyad
Basel Eyad

Reputation: 5

How can I get only the first character entered by the user?

Hangman

I'm using scanf to get a character entered by the user (guessed letter), but it seems like scanf gets all the letters entered

        char guessed_letter;
        printf("\n");

        scanf(" %c", &guessed_letter);


enter image description here

if the word is moon


if the user entered moo this happens

m _ _ _

m o _ _

m o o _

but what I'm expecting is to read only the first one.

m _ _ _

this problem aslo occures when counting mistakes because it scans more than one charachter

I'm scanning for the letter in a do while loop, because I want the user to keep guessing

Upvotes: 0

Views: 65

Answers (1)

cagriyalniz
cagriyalniz

Reputation: 51

this code will work for you. first of all you take the whole word from the user. because the users want to write whole word not a just character. (by the way if you don't want to deal with the "malloc", you can use the strdup. but i suggest learn to the malloc.) The first letter of the character from the user is the value you want. you can write it by its first index (guessed_letter[0]).

#include <stdio.h>
#include <string.h>
int main()
{
    char *guessed_letter = strdup("");
    printf("\n");
    scanf("%s", guessed_letter);
    printf("first character is: %c", guessed_letter[0]);


}

Upvotes: 1

Related Questions