So as a beginner in C and programming in general I try to write a little "hangman" game. Outside of main(), there's two functions, one that get user's attempts and one that actually check if the character is in the word, and loop until user's has found the word. Here it is:
The main.c:
/*GAME OF HANGMAN*/
#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
int main(void)
{
/*Menu*/
int menuChoice = 0;
printf("***********\n");
printf("* HANGMAN *\n");
printf("***********\n\n");
printf("1.Play\n");
printf("2.Quit\n");
scanf("%d", &menuChoice);
switch (menuChoice)
{
case 1:
fflush(stdin);
printf("Let's Play!\n");
game();
break;
case 2:
printf("Bye!\n");
exit(0);
break;
default:
printf("Error.\n");
break;
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
functions.c:
//Get User Attempts
char userinput(void)
{
char input = 0;
input = getchar();//get user attempt
input = toupper(input);//make 'input' uppercase if it's not
while(getchar() != '\n');//read the \n to flush it from memory
return input;//return user attempt
}
//Actuall game
void game(void)
{
char secret[] = "HELLO";//To find
char hiden[] = "*****";//Hidden word
int wsize = 5;//It's size.
do
{
printf("%s\n", hiden);
printf(">");
char try = userinput();
int i = 0;
for(i = 0; i < wsize; i++)
{
//replace stars by found letters.
if(try == secret[i])
{
hiden[i] = secret[i];
}
}
}while(strcmp(hiden, secret) != 0); //Loop until found the word
printf("Congrats, the word was %s!\n", secret);
} `
(I don't show the "main" file/function because it only serve as a menu that redirect to game(void).)
The word to find is "hard-coded", I'll make it pick it randomly from a file when this works.
Whenever I run it, the first user's input is completely ignored, right or wrong, and from the second attempt it works properly.
I tried removing the while(getchar() != '\n') It then stop ignoring the first attempt but display ">*****" instead of just ">".
I really dont understand what's going on, any help would be much appreciated!
Sorry for my bad english and thanks in advance.