@zeus, It's better to use toupper.
@obvious, Here's how I might do it, but it's not well-tested.
Exposing the first letter is kind of strange. That's not usually how hangman works. Also, it would be useful to show the unguessed letters. And only allowing 6 guesses might not work for longer words!
Modern style is to declare variables (and initialize them if possible) where they are first used, not all at the top of the function. In particular, loop indices should be declared in the for loop head.
Your variable names are generally too long. It just makes things less readable. The rule of thumb (smack!) is, the larger the scope, the longer the name. So, all things being equal, i is better than index (or counter).
For boolean values you can include <stdbool.h> and use bool, true, and false instead of int, 1, and 0.
"end of ..." comments are just clutter.
It is "undefined behaviour" to flush the input stream. It apparently works as you might expect in windows, which is very handy, but unfortunately it doesn't work in linux. It's best to try write the program so that it is not needed, and when it is needed, use getchar() in a loop until you read the newline.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORD 100
int get_word(char *word, int size) {
fgets(word, size, stdin);
int len = strlen(word);
if (len && word[len - 1] == '\n')
word[--len] = '\0';
for (int i = 0; i < len; ++i)
if (isalpha(word[i]))
word[i] = toupper(word[i]);
else
return -1;
return len;
}
void create_output(char *output, int len) {
for (int i = 0; i < len; ++i)
output[i] = '_';
output[len] = '\0';
}
void print_output(const char *output, const char *alpha, int tries) {
printf("(%d) ", tries);
for (int i = 0; output[i]; ++i)
printf("%c ", output[i]);
printf(" %s\n", alpha);
}
bool play_game(const char *word, int len) {
char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char output[MAX_WORD];
create_output(output, len);
int tries = 0, guessed = 0;
while (tries < len && guessed < len) { // using word length for number of tries (?!)
print_output(output, alpha, tries);
printf("Guess: ");
char guess;
scanf(" %c", &guess);
guess = toupper(guess);
if (alpha[guess - 'A'] != ' ') {
for (int i = 0; i < len; ++i)
if (word[i] == guess && output[i] == '_') {
output[i] = word[i];
++guessed;
}
alpha[guess - 'A'] = ' ';
++tries;
}
}
print_output(output, alpha, tries);
return guessed == len;
}
int main() {
printf("Enter word to guess: ");
char word[MAX_WORD];
int len = get_word(word, sizeof word);
if (len == -1) {
printf("The word cannot contain spaces.\n");
return EXIT_FAILURE;
}
if (play_game(word, len))
printf("You win!\n");
else
printf("You lose.\nThe word was %s.\n", word);
return 0;
}