I'm somewhat new to C/C++ and I don't get what my problem in the following code is. In this assignment I am restricted to use C-functions and syntax only, no C++ allowed.
The programm should choose a random character from the alphabet and give the user 3 tries to guess it.
#include <stdio.h>
#include <stdlib.h>
#define guesses 3
int main(){
setbuf(stdout, NULL);
/* A 2.P.b */
/* version with loop*/
int i = 0;
char randomChar = (65 + (rand()%26) + 1);
/* comment the line below, when the programm works as intended */
printf("\n%c\n", randomChar);
char guessedChar;
while((i<=guesses) && (guessedChar != randomChar)){
printf("Guess a letter.\n");
scanf("%c", &guessedChar);
if(guessedChar != randomChar){
int guessesLeft = guesses - i;
if (guessesLeft > 1){
printf("Wrong letter. You have %d more tries.\n", guessesLeft);
}
else{
printf("Wrong letter. Last try.");
}
}
else{
printf("Congratulations.\n");
}
i++;
}
return 1;
}
The output is as follows:
Q
Guess a letter.
A
Wrong letter. You have 3 more tries.
Guess a letter.
Wrong letter. You have 2 more tries.
Guess a letter.
B
Wrong letter. Last try.Guess a letter.
Wrong letter. Last try.
The problems:
The chosen letter is NOT random, but always Q.
The first guess takes costs two "lives" ?!