Basic C hangman code problems - c

Hey guys im learning C and i started programming a Hangman Game. That should be played over 1 word and i choosed "informatik".
What i want to do is asking for users name and then start.
#include<stdio.h>
int main() {
int correct = 0;
int mistake = 0;
int number = 0;
char name[20];
char Word[]={'i','n','f','o','r','m','a','t','i','k'};
char guessStatus[]={'_','_','_','_','_','_','_','_','_','_','\0'};
char guess;
printf("##### Welcome to Hangman #####\nWhat is your Name?\n");
scanf(" %s", name);
fflush(stdin);
printf("Hello %s!\n", name);
while (mistake <=10 && number<10) {
printf("Guess a letter: ");
guess = getchar();
printf("%c", guess);
correct = 0;
for (int search=0; search<10; search++)
{
if (guess == Word[search]){
number++;
guessStatus[search] = Word[search];
correct = 1;
}
}
if (correct == 0){
mistake++;
printf("%c is wrong!\nYour Status is: %s\nYou have %i tries left\n", guess,guessStatus,10-mistake);
}
else {
printf("Good job %s!\nYour Status is: %s\nYou have %i tries left\n", name,guessStatus,10-mistake);
}
}
}
Problem is when i run the code and enter any letter, program counts "enter" also as a letter.I used fflush(stdin) as a hope even i don't know anything about it but didn't work :)
Problem output like:
Welcome to Hangman
What is your Name?
john
Hello john!
Guess a letter:
is wrong!
Your Status is: __________
You have 9 tries left
Guess a letter: i
iGood job john!
Your Status is: i_______i_
You have 9 tries left
Guess a letter:
is wrong!
Your Status is: i_______i_
You have 8 tries left
I don't know how to deal with it.Help would be very appreciated.

Add the gethcar(); will be ok for read the \n:
#include <stdio.h>
int main() {
int correct = 0;
int mistake = 0;
int number = 0;
char name[20];
char Word[]={'i','n','f','o','r','m','a','t','i','k'};
char guessStatus[]={'_','_','_','_','_','_','_','_','_','_','\0'};
char guess;
printf("##### Welcome to Hangman #####\nWhat is your Name?\n");
scanf(" %s", name);
getchar(); // add this line
printf("Hello %s!\n", name);
while (mistake <=10 && number<10) {
printf("Guess a letter: ");
guess = getchar();
printf("%c", guess);
correct = 0;
for (int search=0; search<10; search++)
{
if (guess == Word[search]){
number++;
guessStatus[search] = Word[search];
correct = 1;
}
}
if (correct == 0){
mistake++;
printf("%c is wrong!\nYour Status is: %s\nYou have %i tries left\n", guess,guessStatus,10-mistake);
}
else {
printf("Good job %s!\nYour Status is: %s\nYou have %i tries left\n", name,guessStatus,10-mistake);
}
}
}

try this it should work
Use
scanf(" %c",&guess);
instead of
guess = getchar(); //remove this line
printf("%c", guess); //remove this line also

Related

Number guessing game always returns the same output

I'm making a simple number guessing game from 1 - 10 using an if...else statement, it worked the first time, but it seems it always outputs "You didn't guess it correctly." when I'm guessing or the other way around. Would be great for some help, so here are the solutions I made as of asking this question:
//This is the first solution I've come up with.
#include <stdio.h>
#include <stdbool.h>
int main() {
int guessingNumber = '5';
printf("Guess from 1-10: ");
scanf("%d", &guessingNumber);
if (guessingNumber == true) {
printf("You guessed it!\n");
}
else {
printf("You didn't guess it correctly.\n");
}
return 0;
}
//Here is the second one.
#include <stdio.h>
int main() {
int guessingNumber = '5';
int guess;
printf("Guess from 1-10: ");
scanf("%d", &guess);
if (guessingNumber == guess) {
printf("You guessed it!\n");
}
else {
printf("You didn't guess it correctly.\n");
}
return 0;
}
I'm sure that the problem causing this is in this lines from the first solution:
printf("Guess from 1-10: ");
scanf("%d", &guessingNumber);
if (guessingNumber == true) {
printf("You guessed it!\n");
and this from the second solution that I'm sure the problem (might also) came:
printf("Guess from 1-10: ");
scanf("%d", &guess);
if (guessingNumber == guess) {
printf("You guessed it!\n");
The comparison is unsafe int and a bool. Check the following.
int main()
{
int actualNumber, guessingNumber = 5;
printf("Guess from 1-10: ");
scanf_s("%d", &actualNumber);
if (guessingNumber == actualNumber) {
printf("You guessed it!\n");
}
else {
printf("You didn't guess it correctly.\n");
}
return 0;
}

Is my do while loop not working due to this function?

Im making a program where it asks the user to guess a number 1-100 that the computer is thinking about.
In the end of the program, when the user has guessed the correct number, im trying to get the program to ask if user wants to play again (restart the program).
To solve this, i tried using a do while loop & char repeat;. The loop is stretching from almost the beginning of the program, until the end, althought without success. Does anyone know what im doing wrong? Is it because of the function talfunktion, that the loop won't pass?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int talfunktion (int tal, int guess, int tries, char repeat);
int main () {
do {
srand(time(NULL));
int tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
int guess; //guess is the guessed value of the user
int tries = 0; // amount of tries it took until getting correct
char repeat;
printf("Psst, the right number is: %d \n", tal); // remove later, not relevant to uppg.
printf("Im thinking of a number between 1 and 100, guess which!");
printf("\nEnter: ");
scanf("%d", &guess);
guess = talfunktion(tal, guess, tries, repeat);
getchar();
getchar();
return 0;
}
int talfunktion(int tal, int guess, int tries, char repeat) {
do {
if (guess < tal) {
tries++;
printf("\nYour guess is too low, try again!");
printf("\nEnter: ");
scanf("%d", &guess);
}
else if (guess > tal) {
tries++;
printf("\nYour guess is too high, try again!");
printf("\nEnter: ");
scanf("%d", &guess);
}
} while (guess > tal || guess < tal);
if (guess == tal) {
printf("\nCongratulations, that is correct!");
tries++;
printf("\nYou made %d attempt(s)", tries);
printf("\nPlay Again? (y/n)");
scanf("%c", &repeat);
}
} while (repeat == 'y' || repeat == 'Y');
}
This is one possible solution
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void talfunktion(int tal, int guess, int* tries)
{
if (guess < tal)
{
(*tries)++;
printf("\nYour guess is too low, try again!");
}
else if (guess > tal)
{
(*tries)++;
printf("\nYour guess is too high, try again!");
}
else if (guess == tal)
{
(*tries)++;
printf("\nCongratulations, that is correct!");
printf("\nYou made %d attempt(s)", *tries);
}
}
int main (void)
{
int tal; //tal is the correct value that the code is thinking of
int guess; //guess is the guessed value of the user
int tries = 0; // amount of tries it took until getting correct
char playAgain;
do {
srand(time(NULL));
tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
printf("\nIm thinking of a number between 1 and 100, guess which!");
printf("\nEnter: ");
scanf("%d", &guess);
talfunktion(tal, guess, &tries);
printf("\nPsst, the right number is: %d", tal); // remove later, not relevant to uppg.
getchar(); //to halt the code for taking the input
if(guess == tal)
{
tries = 0;
printf("\nPlay Again? (y/n)\n");
scanf("%c", &playAgain);
}
} while (playAgain != 'n');
return 0;
}
There are several things mentioned in the comments that describe problems,
Things you should look at:
Do not define a function inside another function
be careful where you place return statements
when using character testing, use char type for variable
consider simplifying your logical comparisons. (eg guess > tal || guess < tal is the same as guess != tal )
make sure automatic variables are placed such that they are visible where used.
Place space in format specifier: " %c" for scanf() to consume newline character. (instead of excessive use of getchar())
Here is a simplified version of your code, with modified main and talfunktion functions...
char talfunktion(int tal);
int main (void) {
int tal=0;//remove from inside {...} to make it visible to rest of function
char repeat = 'n';
srand(time(NULL));
tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
do {
repeat = talfunktion(tal);
}while((tolower(repeat) == 'y'));
return 0;
}
char talfunktion(int tal)//do all relevant work in function and return
{ //only what is necessary
int guess = 0;
char repeat = 'n';
printf("Im thinking of a number between 1 and 100, guess which!");
printf("\nEnter a number from 1 to 100: ");
scanf("%d", &guess);
if((guess < 1) || (guess > 100))
{
printf("Entered out of bounds guess...\n");
}
else if (guess != tal)
{
if(guess < tal) printf("guess too small\n");
else printf("guess too large\n");
printf("Try again? <'n' or 'y'>\n");
scanf(" %c", &repeat);//space in format specifier to consume newline character
if(tolower(repeat) != 'y') return 'n';//tolower() allows both upper and lower case
}
else
{
printf("Congratulations: You guessed right.\n");
printf("Play again? <'n' or 'y'>\n");
scanf(" %c", &repeat);
}
return repeat;
}

Hangman game - C

Im doing a hangman game as a school project but Im facing an issue:
do{
system("cls");
// Header of the game
printf("\n HANGMAN GAME\n\n\n");
// Present letters found
for (i=0; word[i]!='\0'; i++)
printf (" %c ", word_2[i]);
printf("\n");
// Present positions to the letters
for (i=0; word[i]!='\0'; i++)
printf("___ ");
printf("\n");
// ****PLAYER'S ANSWERS*****
// Read player's answers
printf("\n\n Whats your guess + <enter>: ");
scanf("%c", &letter);
scanf("%c", &c);
// Verify if the letter is in the word
found=0;
for(i=0; word[i]!='\0'; i++)
if (word[i] == letter){
word_2[i] = letter;
corrects++;
max_attemps--;
found = 1;
printf("\nWell done, %s. You have now %d attempts\n\n", name, max_attemps);
system("pause");
}
if(found == 0){
max_attemps--;
printf("\nOh no, %s. You have now %d attempts\n\n", name, max_attemps);
system("pause");
}
if (max_attemps <= 0 || corrects == lenght) {
end = 1;
}
} while (end == 0);
When I got a right letter that have two or more position in the word it takes from me two or more attempts because of the system("pause") when in fact just had to takes me one. But if I don't put the system("pause") the board will be cleared before I can see the message. Anyone knows what can I do to solve this? I'll be very grateful.
Check your found flag only after you have scanned the whole word:
// Verify if the letter is in the word
found=0;
for(i=0; word[i]!='\0'; i++)
if (word[i] == letter){
word_2[i] = letter;
corrects++;
max_attemps--;
found = 1;
// comment out
// printf("\nWell done, %s. You have now %d attempts\n\n", name, max_attemps);
// system("pause");
}
if(found == 1)
{
printf("\nWell done, %s. You have now %d attempts\n\n", name, max_attemps);
system("pause");
}
else{
max_attemps--;
printf("\nOh no, %s. You have now %d attempts\n\n", name, max_attemps);
system("pause");
}
if (max_attemps <= 0 || corrects == lenght) {
end = 1;
}

How to end the program when a user enters "quit"

How can I end the program when a user enters "quit"? I tried an if statement before the loop and within the loop. I'm pretty new to programming and it's bothering me that I can't figure this out. I even tried a do while loop and that didn't work at all.
int main()
{
char word[30];
char yn;
int loopcount;
yn=0;
loopcount=0;
printf("Enter a word:");
scanf(" %s", word);
printf("Would you like to change the word? y=yes, n=no \n");
scanf(" %c", &yn);
if (yn=='n')
{
return 0;
}
while(yn>0)
{
printf("Enter a new word: \n");
scanf(" %s", word);
printf("New word is: %s \n");
loopcount= loopcount+1;
printf("You have changed the word %d times.\n", loopcount);
printf("Would you like to change the word? y=yes, n=no\n");
scanf(" %c", &yn);
if (yn=='n')
{
return 0;
}
return 0;
}
return 0;
}
Use strcmp()
scanf(" %s", word);
if (strcmp(word, "quit") == 0) {
return 0;
}

Why does this C loop skip the first attempt to input a letter?

This is a program I am making for a class. It is supposed to read a letter from a file, and then in the game the user tries do guess the letter. with every wrong attempt the program tells you if the actual letter comes before or after your guess in the alphabet.
For some reason when I run it, the loop skips the first attempt in the getLetter function and does not let you input the letter. Why is this?
#include <stdio.h>
#include <ctype.h>
#define MaxGuesses 5
void instructions();
int playGuess (char solution);
char getLetter ();
int compareLetters (char guess, char solution);
int main()
{
int numGames;
int i;
char solution;
char guess;
int result;
FILE *inFile;
inFile=fopen("inputLet.txt","r");
instructions();
scanf("%d", &numGames);
for(i=1; i<=numGames; i++)
{
printf ("\nThis is game %d\n", i);
fscanf(inFile, " %c", &solution);
result = playGuess(solution);
if (result == 1)
printf("You've WON!\n");
else
printf("You've LOST :(\n");
}
//close file
fclose(inFile);
return 0;
}
void instructions ()
{
printf ("This game consists of guessing letters.\nThe user will have up to 5 chances of guessing correctly,\nupon every failed attempt,\na hint will be provided regarding alphabetical position.\n\nEnter the number of games you wish to play (max 4): ");
}
char getLetter()
{
char userGuess;
printf("\nPlease enter your guess: ");
scanf("%c", &userGuess);
userGuess = tolower(userGuess);
return userGuess;
}
int compareLetters(char guess, char solution)
{
if (guess == solution)
return 1;
else if (guess < solution)
{
printf("\nThe letter that you are trying to guess comes before %c", guess);
return 0;
}
else if (guess > solution)
{
printf("\nThe letter that you are trying to guess comes after %c", guess);
return 0;
}
}
int playGuess (char solution)
{
int numGuesses = 0;
int winOrLose = 0;
char guess;
while(numGuesses < MaxGuesses && winOrLose == 0)
{
guess = getLetter();
winOrLose = compareLetters(guess, solution);
numGuesses++;
}
return winOrLose;
}
It may be consuming a character left in the input buffer (possibly a newline or other whitespace character). You could try changing the format string from "%c" to " %c" as you've done elsewhere, which will skip all the whitespace characters in the buffer before trying to read a character.

Resources