一个简单的猜谜游戏,继续使用除声明变量Y/N之外的任何其他字母

Simple guessing game continuing with any other letter other than the declared variable Y/N

本文关键字:变量 声明 其他 任何 一个 简单 继续 游戏      更新时间:2023-10-16

我是一名有抱负的开发人员,我正在学习我的第一门语言C++。我用从互联网和YouTube上学到的东西制作了一个简单的猜谜游戏。几乎电脑会随机生成一个0到5之间的数字,你必须输入哪个数字才是正确的。

问题是,在程序询问你的名字(没有存储)后,会询问你是否想玩一个要求y或n的游戏。y继续,n关闭程序。

假设Y继续游戏,但如果我再加一个字母,例如g,它将继续游戏。我该如何修复代码以只允许变量"y/y"继续游戏?

下面是代码。

#include <iostream>
#include <Windows.h>
#include <cmath>
#include <ctime>
#include <string>
using namespace std;
int main()
{
    int num, numrand;
    char yn;
    string name;
    srand(time(NULL));
    cout << "Welcome to the program and please enter your name:";
    cin >> name;
    while (true)
    {
        cout << "Hello " << name << " do you want to play a game? (y/n): ";
        cin >> yn;
        if (yn == 'n' || yn == 'N')
            return 0;
        if (yn == 'y' || yn == 'Y');
        break;
        //If any other letter is used then it will continue. how to fix?
    }
    while (true)
    {
        cout << "computer will imagine one number from 0 to 5 and you will be given the task to guess it: ";
        cin >> num;
        numrand = rand() % 6;
        if (numrand == num)
            cout << "You Win!" << endl;
        else if (num == -1)
            break;
        else
            cout << "You Lose! The computer imagined the number: "<< numrand << endl;
    }

    system("pause");
    return 0;
}

在if语句之后和break之前有一个意外的分号。