Hangman code in C

I would suggest providing functions for this code. The code is difficult to read and follow. Start with first creating a menu function, then get user input function; also do checks with-in the function that verify that the input if valid before it sends a character back. Then check to see if the guess is correct and post the response using a function. You will find that if you draw out your code and create the necessary functions it will be much easier to follow and debug.

print_menu() displays the options for the user and an exit choice.

get_user_input() gets the user input with checking to see that it is valid input

print_remaining() prints remaining and guessed characters of the word at play

Note if you for instance are getting a char from the user and they enter a letter.

 scanf_s("%c", &guess, _countof(guess));   

Note: _countof(ArrayName) simply just verifies that there is enough space for the placement of the char or string that is going to be assigned. Make sure to #include “stdlib.h” file for this function.

The reason for using scanf_s is that it reads over whitespaces. It dose not read the bad input and if you encounter some from the user, it puts the bad input back into the input buffer where it got if from. The scanf_s() has a return value and its value is going to be how many correct input responses were filled. Meaning this if %c actually read a char then the return value will be 1. if you got a 4 for the entry it will put the four back and return a 0. Good way to read input. getchar() also works well with this but has some detailed conditions that could cause some grief if not understood. Would be something to consider.

while(scanf_s("%c", &guess, _countof(guess)) != 1 )  
 // clear the input buffer and then try again.

Then you just clear the input buffer with

 while(getchar() != '\n')  

Above: Clears everything in the input buffer up to and including the newline char. Then, ask the user to enter valid input this time.

If you getting stuff that is printing twice that tells me that the loop is running past its exit condition. If your exit condition has anything to do with reading input. The above loop will take care of any information chillen in the input buffer. Hope this helps. Focus on only calling functions in the actual code. Makes debugging much easier.

Browse More Popular Posts

Leave a Comment