Hangman Game in C++

 

Introduction

The Hangman game is a popular word guessing game where players try to guess a hidden word by suggesting letters within a certain number of guesses.
The goal of this game is to guess the word correctly before running out of attempts, which are typically represented by drawing parts of a hangman figure.

Objective

The objective of this task is to implement the Hangman game using the C++ programming language. In this game, the program randomly selects a word from a list,
and the player must guess the word by inputting letters. The game will display the number of correct guesses and the remaining attempts. If the player guesses all letters of the word correctly within the given attempts, they win. If they run out of attempts, they lose.

Hangman Game Code in C++

#include 
#include 
#include 
#include 

using namespace std;

// Function to print the current state of the game (word with guessed letters)
void displayWord(const string &word, const string &guessedLetters) {
    for (int i = 0; i < word.length(); ++i) {
        if (guessedLetters.find(word[i]) != string::npos)
            cout << word[i] << " ";
        else
            cout << "_ ";
    }
    cout << endl;
}

// Function to check if the player has guessed the word correctly
bool isWordGuessed(const string &word, const string &guessedLetters) {
    for (int i = 0; i < word.length(); ++i) {
        if (guessedLetters.find(word[i]) == string::npos)
            return false;
    }
    return true;
}

int main() {
    string words[] = {"programming", "computer", "hangman", "game", "cplusplus"};
    int numWords = sizeof(words) / sizeof(words[0]);

    // Randomly select a word from the list
    srand(time(0));
    string word = words[rand() % numWords];

    string guessedLetters = "";  // Stores guessed letters
    int attempts = 6;  // Number of attempts before losing the game

    cout << "Welcome to the Hangman Game!" << endl; // Game loop while (attempts > 0) {
        cout << "\nWord to guess: ";
        displayWord(word, guessedLetters);
        cout << "Guessed letters: " << guessedLetters << endl;
        cout << "Remaining attempts: " << attempts << endl;
        
        cout << "Enter a letter to guess: "; char guess; cin >> guess;
        
        // Check if the letter is already guessed
        if (guessedLetters.find(guess) != string::npos) {
            cout << "You've already guessed that letter!" << endl;
            continue;
        }

        // Add the guessed letter to the guessedLetters string
        guessedLetters += guess;

        // Check if the guess is correct
        if (word.find(guess) == string::npos) {
            attempts--;  // Decrease attempts if the guess is incorrect
            cout << "Incorrect guess!" << endl;
        } else {
            cout << "Correct guess!" << endl;
        }

        // Check if the player has won
        if (isWordGuessed(word, guessedLetters)) {
            cout << "\nCongratulations! You've guessed the word: " << word << endl;
            break;
        }
    }

    if (attempts == 0) {
        cout << "\nSorry, you've lost! The word was: " << word << endl;
    }

    return 0;
}

Explanation of the Program Structure

The Hangman game in C++ is implemented using standard input and output. Here is an explanation of how the program works:

  • Word Selection: A predefined list of words is provided, and the program selects a random word using rand() function.
  • Display the Word: The displayWord() function shows the current state of the word, replacing unguessed letters with underscores (“_”).
  • Input Handling: The user is asked to input a letter. The program checks whether the input letter has already been guessed or not.
  • Guess Evaluation: If the guessed letter is correct, it is added to the list of guessed letters. If incorrect, the number of remaining attempts is decreased.
  • Game Over Conditions: The game ends if the player either guesses all letters of the word correctly (win) or runs out of attempts (lose).

How to Run the Program:

1. Copy the code into a C++ compiler or IDE like Code::Blocks, Visual Studio, or an online compiler.

2. Compile the program. In most IDEs, this can be done by pressing the “Build” or “Compile” button.

3. Run the program. The terminal or console window will display the game and prompt for inputs.

4. Play the game by guessing letters, and try to guess the word before you run out of attempts!

Copyright © 2024 Learn Programming. All Rights Reserved.

 

24 Replies to “Hangman Game in C++”

  1. I am extremely impressed with your writing skills and also with the layout in your blog. Is this a paid subject or did you customize it your self? Anyway stay up the excellent high quality writing, it’s rare to look a nice weblog like this one today!

  2. What you’re creating here is a true oasis of knowledge and inspiration! Every sentence is like a precious pearl, and together they form a fascinating necklace of wisdom. The only thing I found missing was slightly more detailed examples – that would have made it absolutely perfect!

  3. I intended to post you a very little remark just to say thanks a lot once again over the fantastic concepts you’ve documented at this time. This has been so particularly open-handed of people like you to allow unreservedly all that most of us could have supplied for an e book to help make some profit for themselves, notably seeing that you could possibly have tried it if you wanted. The things likewise acted like a great way to fully grasp that other individuals have the identical eagerness similar to my very own to learn somewhat more around this matter. I’m sure there are a lot more pleasurable occasions in the future for individuals that go through your blog post.

  4. Scopri Crazy Time con croupier dal vivo su un casino ADM sicuro con cashback settimanale e transazioni sicure.

    Crea il tuo account oggi e gioca con soldi reali ogni giorno!

    crazytime live stream [url=http://clearcreekgamefowl.com/]https://clearcreekgamefowl.com/[/url]

  5. تتضمن 888starz مصر مجموعة واسعة من الألعاب الرياضية والأحداث التي يمكن للمستخدمين المشاركة فيها
    888starz تسجيل الدخول [url=888starz.onl/eg]https://888starz.onl/eg/[/url]
    888starz Egypt تُقدم عروض وتخفيضات đặc biệt للمستخدمين الجدد

  6. 888starz مصر تهتم برعايه العملاء و توفير تجربة مميزه لهم
    8888 starz [url=https://www.888starz.onl/eg/]https://888starz.onl/eg/[/url]
    888starz مصر تُقدم فرصاً لمراهنة مباشرة على الأحداث الرياضية

  7. تعتبر 888starz من الشركات المرموقة فى مجال المراهنات الرياضية فى مصر
    تسجيل دخول 888starz [url=https://www.888starz.onl/eg]https://888starz.onl/eg/[/url]
    888starz Egypt تتميز بتوفر العديد من طرق الدفع الآمنة

  8. تعتبر 888starz من الشركات المرموقة فى مجال المراهنات الرياضية فى مصر
    ٨٨٨ ستارز [url=https://888starz.onl/eg/]https://888starz.onl/eg/[/url]
    888starz Egypt تتميز بتوفر العديد من طرق الدفع الآمنة

  9. تتضمن 888starz مصر مجموعة واسعة من الألعاب الرياضية والأحداث التي يمكن للمستخدمين المشاركة فيها
    كازينو 888 تسجيل الدخول [url=https://888starz.onl/eg]https://888starz.onl/eg/[/url]
    888starz Egypt تُمكن المستخدمين من المشاركة في بطولات دولية ومحلية

  10. XEvil 6.0 automatically solve most kind of captchas,
    Including such type of captchas: ReCaptcha v.2, ReCaptcha v.3, Google, SolveMedia, BitcoinFaucet, Steam, +12k
    + hCaptcha, FC, ReCaptcha Enterprize now supported in new XEvil 6.0!
    + CloudFlare TurnsTile, GeeTest captcha now supported in new XEvil 7.0!
    + XEvil 7.0 was released! ReCaptcha v2 solving speed increased x2!
    + XEvil can solve captchas from OpenClaw AI bot!

    1.) Fast, easy, precisionly
    XEvil is the fastest captcha killer in the world. Its has no solving limits, no threads number limits

    2.) Several APIs support
    XEvil supports more than 6 different, worldwide known API: 2Captcha, anti-captchas (antigate), rucaptcha, death-by-captcha, etc.
    just send your captcha via HTTP request, as you can send into any of that service – and XEvil will solve your captcha!
    So, XEvil is compatible with hundreds of applications for SEO/SMM/password recovery/parsing/posting/clicking/cryptocurrency/etc.

    3.) Useful support and manuals
    After purchase, you got access to a private tech.support forum, Wiki, Skype/Telegram online support
    Developers will train XEvil to your type of captcha for FREE and very fast – just send them examples

    4.) How to get free trial use of XEvil full version?
    – Try to search in Google “Home of XEvil”
    – you will find IPs with opened port 80 of XEvil users (click on any IP to ensure)
    – try to send your captcha via 2captcha API ino one of that IPs
    – if you got BAD KEY error, just tru another IP
    – enjoy! 🙂
    – (its not work for hCaptcha!)

    WARNING: Free XEvil DEMO does NOT support ReCaptcha, hCaptcha and most other types of captcha!

  11. XEvil 5.0 automatically solve most kind of captchas,
    Including such type of captchas: ReCaptcha-2, ReCaptcha v.3, Google captcha, SolveMedia, BitcoinFaucet, Steam, +12000
    + hCaptcha, FC, ReCaptcha Enterprize now supported in new XEvil 6.0!
    + CloudFlare TurnsTile, GeeTest captcha now supported in new XEvil 7.0!
    + XEvil 7.0 was released! ReCaptcha v2 solving speed increased x2!
    + XEvil can solve captchas from OpenClaw AI bot!

    1.) Fast, easy, precisionly
    XEvil is the fastest captcha killer in the world. Its has no solving limits, no threads number limits

    2.) Several APIs support
    XEvil supports more than 6 different, worldwide known API: 2Captcha, anti-captcha (antigate), rucaptcha, DeathByCaptcha, etc.
    just send your captcha via HTTP request, as you can send into any of that service – and XEvil will solve your captcha!
    So, XEvil is compatible with hundreds of applications for SEO/SMM/password recovery/parsing/posting/clicking/cryptocurrency/etc.

    3.) Useful support and manuals
    After purchase, you got access to a private tech.support forum, Wiki, Skype/Telegram online support
    Developers will train XEvil to your type of captcha for FREE and very fast – just send them examples

    4.) How to get free trial use of XEvil full version?
    – Try to search in Google “Home of XEvil”
    – you will find IPs with opened port 80 of XEvil users (click on any IP to ensure)
    – try to send your captcha via 2captcha API ino one of that IPs
    – if you got BAD KEY error, just tru another IP
    – enjoy! 🙂
    – (its not work for hCaptcha!)

    WARNING: Free XEvil DEMO does NOT support ReCaptcha, hCaptcha and most other types of captcha!

    http://xrumersale.site/

  12. Wspolczesne uvula temat ten przyciaga uwage wielu graczy, ktorzy szukaja bezpiecznych i rozbudowanych platform do zabawy. Glowny aspekt to przede wszystkim dostepnosc gier, ktore lacza wysoka jakosc grafiki z plynna rozgrywka. Wulkaniczne sila tej marki polega na roznorodnosci tytulow, od klasycznych slotow po nowoczesne automaty z interaktywnymi funkcjami.

    Dla poczatkujacych uzytkownikow kluczowe jest zrozumienie, jak dziala vulkan spiele casino polska i jak rozpoczac gre w bezpieczny sposob. Pierwsza kroki obejmuja rejestracje na platformie, weryfikacje konta oraz wybor preferowanych metod platnosci. Kluczowym elementem jest rowniez zapoznanie sie z regulaminem i polityka prywatnosci, aby uniknac nieprzyjemnych niespodzianek. Nastepnie krokiem jest zrozumienie zasad bonusow, ktore czesto towarzysza uruchomieniu konta. Swietnie jest skonsultowac sie z obsluga klienta w razie pytan, poniewaz profesjonalne doradztwo zwieksza komfort gry. Po krotkiej chwili mozna przetestowac darmowe tryby i dopasowac ustawienia do swoich preferencji.

    kasyno vulkanspiele [url=raapchikcraft.com/kasyno-vulkan-spiele-vulkanspiele-pl-2026]https://raapchikcraft.com/kasyno-vulkan-spiele-vulkanspiele-pl-2026/[/url]

  13. يغطي القسم الثالث نطاق الألعاب وتشكيلة الخيارات التي تتيحها المنصة للمستخدمين.
    888starz للايفون [url=https://rybflot.com/888starz-apk-ios/]https://rybflot.com/888starz-apk-ios/[/url]

  14. Казино 888starz радует игроков разнообразием слот-автоматов, . В рамках этой статьи мы рассмотрим, как онлайн-казино 888starz работает в Узбекистане и какие преимущества предоставляет раздел ставок на спорт 888starz. Сервис снабжен лицензией и контролируется надёжными органами, .

    Пользователи Узбекистана могут легко зарегистрироваться на сайте 888starz, . Верификация проходит быстро, что дает возможность сразу пополнить счёт. Сервис обеспечивает быстрые выплаты и богатый выбор развлечений. Абзац 2: Ассортимент слот-машин на 888starz насчитывает проекты от топовых и нишевых компаний. Преимущества слотов включают яркую графику, множество бонусных функций и частые джекпоты, . Раздел настольных игр на платформе также обширен: рулетка, блэкджек, бинго и прочие варианты, .

    зеркало 888starz [url=https://888starzuzz.com]https://888starzuzz.com/[/url]

  15. XEvil 5.0 automatically solve most kind of captchas,
    Including such type of captchas: ReCaptcha-2, ReCaptcha-3, Google captcha, Solve Media, BitcoinFaucet, Steam, +12k
    + hCaptcha, FC, ReCaptcha Enterprize now supported in new XEvil 6.0!
    + CloudFlare TurnsTile, GeeTest captcha now supported in new XEvil 7.0!
    + XEvil 7.0 was released! ReCaptcha v2 solving speed increased x2!
    + XEvil can solve captchas from OpenClaw AI bot!

    1.) Fast, easy, precisionly
    XEvil is the fastest captcha killer in the world. Its has no solving limits, no threads number limits

    2.) Several APIs support
    XEvil supports more than 6 different, worldwide known API: 2captcha, anti-captchas (antigate), rucaptcha, death-by-captcha, etc.
    just send your captcha via HTTP request, as you can send into any of that service – and XEvil will solve your captcha!
    So, XEvil is compatible with hundreds of applications for SEO/SMM/password recovery/parsing/posting/clicking/cryptocurrency/etc.

    3.) Useful support and manuals
    After purchase, you got access to a private tech.support forum, Wiki, Skype/Telegram online support
    Developers will train XEvil to your type of captcha for FREE and very fast – just send them examples

    4.) How to get free trial use of XEvil full version?
    – Try to search in Google “Home of XEvil”
    – you will find IPs with opened port 80 of XEvil users (click on any IP to ensure)
    – try to send your captcha via 2captcha API ino one of that IPs
    – if you got BAD KEY error, just tru another IP
    – enjoy! 🙂
    – (its not work for hCaptcha!)

    WARNING: Free XEvil DEMO does NOT support ReCaptcha, hCaptcha and most other types of captcha!

  16. XEvil 6.0 automatically solve most kind of captchas,
    Including such type of captchas: ReCaptcha v.2, ReCaptcha-3, Google, SolveMedia, BitcoinFaucet, Steam, +12000
    + hCaptcha, FC, ReCaptcha Enterprize now supported in new XEvil 6.0!
    + CloudFlare TurnsTile, GeeTest captcha now supported in new XEvil 7.0!
    + XEvil 7.0 was released! ReCaptcha v2 solving speed increased x2!
    + XEvil can solve captchas from OpenClaw AI bot!

    1.) Fast, easy, precisionly
    XEvil is the fastest captcha killer in the world. Its has no solving limits, no threads number limits

    2.) Several APIs support
    XEvil supports more than 6 different, worldwide known API: 2Captcha, anti-captchas (antigate), RuCaptcha, DeathByCaptcha, etc.
    just send your captcha via HTTP request, as you can send into any of that service – and XEvil will solve your captcha!
    So, XEvil is compatible with hundreds of applications for SEO/SMM/password recovery/parsing/posting/clicking/cryptocurrency/etc.

    3.) Useful support and manuals
    After purchase, you got access to a private tech.support forum, Wiki, Skype/Telegram online support
    Developers will train XEvil to your type of captcha for FREE and very fast – just send them examples

    4.) How to get free trial use of XEvil full version?
    – Try to search in Google “Home of XEvil”
    – you will find IPs with opened port 80 of XEvil users (click on any IP to ensure)
    – try to send your captcha via 2captcha API ino one of that IPs
    – if you got BAD KEY error, just tru another IP
    – enjoy! 🙂
    – (its not work for hCaptcha!)

    WARNING: Free XEvil DEMO does NOT support ReCaptcha, hCaptcha and most other types of captcha!

    http://xrumersale.site/

  17. المكافآت والبرامج الولاء على 888starz تعزز فرص الربح وتضفي حماسة إضافية على اللعب, العروض الترويجية متجددة وتتيح للاعبين فرص ربح مستمرة وميزة السحب السريع, المحتوى التعليمي والإرشادي يساعد اللاعبين على فهم الألعاب وتحسين استراتيجياتهم
    888 [url=https://888starz-egypt-ar.com/]888[/url].

  18. Kasyna w Polsce czesto oferuja vulkanspiele, ktore przenosza graczy w dynamiczny swiat lawy i wybuchow.
    vulkan spiele aktionscode [url=http://www.vulkannclubs.com/kod-promocyjny]https://vulkannclubs.com/kod-promocyjny/[/url]

  19. Aktualne uvula temat ten przyciaga uwage wielu graczy, ktorzy szukaja bezpiecznych i rozbudowanych platform do zabawy. Vulkan aspekt to przede wszystkim dostepnosc gier, ktore lacza wysoka jakosc grafiki z plynna rozgrywka. Wulkaniczne sila tej marki polega na roznorodnosci tytulow, od klasycznych slotow po nowoczesne automaty z interaktywnymi funkcjami.

    Dla poczatkujacych uzytkownikow kluczowe jest zrozumienie, jak dziala vulkan spiele casino polska i jak rozpoczac gre w bezpieczny sposob. Pierwsze kroki obejmuja rejestracje na platformie, weryfikacje konta oraz wybor preferowanych metod platnosci. Kluczowym elementem jest rowniez zapoznanie sie z regulaminem i polityka prywatnosci, aby uniknac nieprzyjemnych niespodzianek. Potem krokiem jest zrozumienie zasad bonusow, ktore czesto towarzysza uruchomieniu konta. Dobrze jest skonsultowac sie z obsluga klienta w razie pytan, poniewaz profesjonalne doradztwo zwieksza komfort gry. Wkrotce potem mozna przetestowac darmowe tryby i dopasowac ustawienia do swoich preferencji.

    kasyno vulkan spiele [url=https://hygienicslife.in/2026/02/18/vulkanspiele-polska-vulkan-spiele-online-casino/]kasyno vulkan spiele[/url].

  20. نبدأ بتحديد تعريف برنامج 888starz وآلية عمله داخل البيئة الرقمية ومتطلبات التسجيل.
    تحميل برنامج 888starz [url=http://www.hellierndt.com/%d8%aa%d8%ad%d9%85%d9%8a%d9%84-%d9%84%d8%b9%d8%a8%d9%87-888starz-%d8%aa%d9%86%d8%b2%d9%8a%d9%84-%d9%88%d8%aa%d8%ab%d8%a8%d9%8a%d8%aa-%d8%a7%d9%84%d9%84%d8%b9%d8%a8%d8%a9-%d8%b9%d9%84%d9%89]https://hellierndt.com/%d8%aa%d8%ad%d9%85%d9%8a%d9%84-%d9%84%d8%b9%d8%a8%d9%87-888starz-%d8%aa%d9%86%d8%b2%d9%8a%d9%84-%d9%88%d8%aa%d8%ab%d8%a8%d9%8a%d8%aa-%d8%a7%d9%84%d9%84%d8%b9%d8%a8%d8%a9-%d8%b9%d9%84%d9%89/[/url]

Leave a Reply to crazy_kwMn Cancel reply

Your email address will not be published. Required fields are marked *