Skip to content

Instantly share code, notes, and snippets.

@cspickert
Created June 19, 2015 22:33
Show Gist options
  • Save cspickert/2ea44c4cd1628c5523fb to your computer and use it in GitHub Desktop.
Save cspickert/2ea44c4cd1628c5523fb to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
int main (int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s word\n", argv[0]);
return 1;
}
char *const wordArg = argv[1];
int const wordLen = strlen(wordArg);
char *word = calloc(wordLen + 1, sizeof(char));
strncpy(word, wordArg, wordLen);
char *underscores = calloc(wordLen + 1, sizeof(char));
for (int i = 0; i < wordLen; i++) {
underscores[i] = '_';
}
underscores[wordLen] = '\0';
printf("Welcome to hangman!\n");
int const maxGuesses = 10;
int swaps = 0;
for (int guess = 0; guess < maxGuesses; guess++) {
printf("%s\n", underscores);
printf("Enter a character: ");
char guess;
scanf("%c", &guess);
fpurge(stdin);
bool swapped = false;
for (int i = 0; i < wordLen; i++) {
if (word[i] == guess) {
char temp = underscores[i];
underscores[i] = word[i];
word[i] = temp;
swaps++;
swapped = true;
}
}
if (!swapped) {
printf("Nope! Try again.\n");
} else if (swaps == wordLen) {
break;
}
}
if (swaps == wordLen) {
printf("You won!\n");
} else {
printf("You lost!\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment