Hello, Im here to ask you guys for help, please, I will very grateful. Im doing a hangman game as a school project but it doesnt working at all.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(){
int ran=0, i=0, end=0, lenght=0;
char word [50], word_2[50], name[20];
int n_words=0, max_attemps, corrects=0, found;
char letter, c;
printf("Whats your name?\n");
scanf ("%s", name);
FILE *arch;
arch = fopen("words.txt", "r");
if (arch==NULL)
{
printf ("Erro opening file");
}
else {
while (!feof(arch)){
fscanf(arch, "%s", &word);
n_words++; // read all the words from the file
}
n_words--;
fclose(arch);
srand (time(NULL));
ran=rand()%(n_words+1); // select random word from the file
}
arch = fopen ("words.txt", "r");
if (arch==NULL){
printf ("Error opening file");
}else{
for(n_words=0; n_words<ran; n_words++)
fscanf(arch, "%s", &word); // save the selected word
}
fclose(arch);
// Define the max number of attemps
for (i=0; word[i]!='\0'; i++){
lenght++;
}
printf("%d\n", lenght);
max_attemps=lenght+2;
//store string with blank characters with the size of the word
for (i=0; word[i]!='\0'; i++)
word_2[i] = '\0';
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("Whats you 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("Well done, %s",name,"You have now %d attemps", max_attemps);
printf ("Whats your guess now?");
}
if(found == 0){
max_attemps--;
printf("Oh no, %s",name,"You have now %d attemps", max_attemps);
printf ("Whats your guess now?");
}
if (max_attemps <= 0 || corrects == lenght) {
end = 1;
}
} while (end == 0);
return(0);
}
The first problem is that:
Code:
printf("Whats your name?\n");
scanf ("%s", name);
If I put this the program doesnt work , but if I dont put it works.
The second is:
Code:
printf("Well done, %s",name,"You have now %d attemps", max_attemps);
printf ("Whats your guess now?");
It doesnt show up when I compile