一个简单的猜谜游戏,继续使用除声明变量Y/N之外的任何其他字母
Simple guessing game continuing with any other letter other than the declared variable Y/N
我是一名有抱负的开发人员,我正在学习我的第一门语言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之前有一个意外的分号。
相关文章:
- 在将变量声明为引用时,堆在释放后使用
- 静态变量声明和定义
- 在变量声明中使用 for 循环
- 向量索引变量声明(size_t 或 std::vector<DATATYPE>::size_type)
- C++ 类型类的变量声明不命名类型?
- 将本地 OpenCV Mat 变量声明为静态以防止重新分配
- std::enable_if 更改成员 *变量* 声明/类型
- 在C++中,变量声明左侧的大括号是什么意思?
- 将变量声明为全局变量,然后声明为局部变量 -Shadowing-
- 命名空间内C++变量声明
- 将静态全局变量声明为内联有什么意义吗?
- 如何将一个变量声明为另一个变量的值
- 如何将迭代器变量声明为私有成员变量
- 没有变量声明为函数,但错误:二进制表达式的操作数无效
- 有没有人有书面证据来保证函数中参数的定义方式与普通变量声明相同?
- ClangTool 如何获取变量声明中模板参数的位置?
- 标准与显式自动推导变量声明
- C 静态变量声明怪异链接器错误
- 如何为数组成员变量声明 getter/setter
- 可视C++变量声明