Консоль выводит тонну гиббери sh после ввода строки с помощью std :: cin в цикл while - PullRequest
0 голосов
/ 13 июля 2020

Я получаю странный вывод gibberi sh на консоль после некоторого времени l oop, чтобы получить подтверждение от игрока, что введено правильное имя.

The l oop отлично работает для проверки уровня сложности, но сходит с ума по подтверждению названия игры.

Вы можете увидеть некоторые из попыток отладки, которые я сделал в функции "SetPlayerName", и все в порядке.

Компилирует нормально, ошибок нет, я изрядно заблудился. Я пробовал .clear и .ignore даже сразу после ввода строки и всего остального, что мог придумать, чтобы точно определить, в чем проблема.

#include <iostream>
#include <ctime>

void PrintGameIntro ()
{
    std::cout << "\nGame Intro Text\n";
} 

// Sets the level constraints for the game as well as getting the desired level and makes sure it's within the constraints so it can be confirmed and SET in SetGameDifficulty
int SelectGameDifficulty ()
{
    int GameDifficulty = 0;
    // Magic numbers for level constraints
    const int MaxLevel = 10;
    const int MinLevel = 1;

    // Get desired level and check that it is within the level constraints
    std::cout << "\nSelect game difficulty 1-10:\n";
    std::cin >> GameDifficulty;
    while (GameDifficulty > MaxLevel || GameDifficulty < MinLevel)
    {
        std::cout << "Please select a level from 1 to 10 or press CTRL-C to exit.\n";
        std::cin >> GameDifficulty;
    }
    return GameDifficulty;
}

// SETS the level difficulty after being SELECTED in SelectLevelDifficulty
int SetGameDifficulty ()
{
    bool bCorrectlevel = false;
    std::string CorrectLevelYesNo = "N";
    while (bCorrectlevel != true)
    {
        const int GameDifficulty = SelectGameDifficulty();
        std::cout << "\nYou selected a game difficulty level of " << GameDifficulty << " is this correct? \n Enter \'(Y)es\' or \'(N)o\'";
        std::cin >> CorrectLevelYesNo;
        if (CorrectLevelYesNo == "Yes" || CorrectLevelYesNo == "Y" || CorrectLevelYesNo == "yes" || CorrectLevelYesNo == "y")
        {
            bCorrectlevel = true;
            return GameDifficulty;
        }
        else
        {
            std::cout << "Please select a difficulty and confirm it.";
        }
    }
}

std::string SetPlayerName()
{
    std::cout << "\nWhat is your name, agent?\n";
    std::string PlayerName;
    std::cin >> PlayerName;
    // BEGIN DEBUG STUFF
    std::cin.clear();
    std::cin.ignore();
    std::cout << "Not gibberish?";
    // END DEBUG STUFF
    bool bCorrectName = false;
    std::string CorrectNameYesNo = "N";
    int NameLoopCount = 1;
    
    // BEGIN DEBUG STUFF
    int TestInt = 15;
    std::cin >> TestInt;
    std::cout << TestInt << PlayerName;
    std::cout << "\nOk, " << PlayerName << ", then. Did I get that right?\n Enter \'(Y)es\' or \'(N)o\'\n";
    std::cin >> TestInt;
    // END DEBUG STUFF
    
    while (bCorrectName = false)
    {
        if(NameLoopCount > 1)
        {
            std::cout << "\nOhh, my mistake. I must be getting deaf in my old age. What was it then?\n";
            std::cin >> PlayerName;
        }
        std::cout << "\nOk, " << PlayerName << ", then. Did I get that right?\n Enter \'(Y)es\' or \'(N)o\'\n";
        std::cin >> CorrectNameYesNo;
        if (CorrectNameYesNo == "Yes" || CorrectNameYesNo == "Y" || CorrectNameYesNo == "yes" || CorrectNameYesNo == "y")
        {
            std::cout << "Alright then, " << PlayerName << ". Let's get started.";
            return PlayerName;
        }
        NameLoopCount ++;
    }
}

int main ()
{
    PrintGameIntro();        
    const int GameDifficulty = SetGameDifficulty();
    std::cin.clear();
    std::cin.ignore();
    const std::string PlayerName = SetPlayerName(); 
    std::cout << "game set to level " << GameDifficulty << " and player name is " << PlayerName <<".";
    return 0;
}

1 Ответ

0 голосов
/ 13 июля 2020

Оказывается, = и == - это не одно и то же. Спасибо за поддержку @ stribor14.

Теперь я знаю, что компилятор полностью в порядке с "плохим" (или, скорее, я думаю, неполным) условием while, и это вызовет

bum bum bummmmmm

переполнение стека хахаха

удалили шаги отладки, которые я ввел, и он работает как задумано

#include <iostream>
#include <ctime>

void PrintGameIntro ()
{
    std::cout << "\nGame Intro Text\n";
} 

// Sets the level constraints for the game as well as getting the desired level and makes sure it's within the constraints so it can be confirmed and SET in SetGameDifficulty
int SelectGameDifficulty ()
{
    int GameDifficulty = 0;
    // Magic numbers for level constraints
    const int MaxLevel = 10;
    const int MinLevel = 1;

    // Get desired level and check that it is within the level constraints
    std::cout << "\nSelect game difficulty 1-10:\n";
    std::cin >> GameDifficulty;
    while (GameDifficulty > MaxLevel || GameDifficulty < MinLevel)
    {
        std::cout << "Please select a level from 1 to 10 or press CTRL-C to exit.\n";
        std::cin >> GameDifficulty;
    }
    return GameDifficulty;
}

// SETS the level difficulty after being SELECTED in SelectLevelDifficulty
int SetGameDifficulty ()
{
    bool bCorrectlevel = false;
    std::string CorrectLevelYesNo = "N";
    while (bCorrectlevel != true)
    {
        const int GameDifficulty = SelectGameDifficulty();
        std::cout << "\nYou selected a game difficulty level of " << GameDifficulty << " is this correct? \n Enter \'(Y)es\' or \'(N)o\'";
        std::cin >> CorrectLevelYesNo;
        if (CorrectLevelYesNo == "Yes" || CorrectLevelYesNo == "Y" || CorrectLevelYesNo == "yes" || CorrectLevelYesNo == "y")
        {
            bCorrectlevel = true;
            return GameDifficulty;
        }
        else
        {
            std::cout << "Please select a difficulty and confirm it.";
        }
    }
}

std::string SetPlayerName()
{
    std::cout << "\nWhat is your name, agent?\n";
    std::string PlayerName;
    std::cin >> PlayerName;
    bool bCorrectName = false;
    std::string CorrectNameYesNo = "N";
    int NameLoopCount = 1;
    
    
    while (bCorrectName == false)
    {
        if(NameLoopCount > 1)
        {
            std::cout << "\nOhh, my mistake. I must be getting deaf in my old age. What was it then?\n";
            std::cin >> PlayerName;
        }
        std::cout << "\nOk, " << PlayerName << ", then. Did I get that right?\n Enter \'(Y)es\' or \'(N)o\'\n";
        std::cin >> CorrectNameYesNo;
        if (CorrectNameYesNo == "Yes" || CorrectNameYesNo == "Y" || CorrectNameYesNo == "yes" || CorrectNameYesNo == "y")
        {
            std::cout << "Alright then, " << PlayerName << ". Let's get started.";
            return PlayerName;
        }
        NameLoopCount ++;
    }
}

int main ()
{
    PrintGameIntro();        
    const int GameDifficulty = SetGameDifficulty();
    const std::string PlayerName = SetPlayerName(); 
    std::cout << "game set to level " << GameDifficulty << " and player name is " << PlayerName <<".";
    return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...