在无效输入后重新提示用户-c++
Reprompt user after invalid input-c++
我修改了原始代码,前两个无效的输入提示可以正常工作。当我在这个提示符中实现相同的逻辑来启动一个新游戏时,我的程序将无法识别无效的输入,输入任何键都会启动一个新游戏。
void newGame()
{
char newGameChoice = 'a';
cout << "n--------------------------------------------------------------------------------" << endl;
cout << "Press N to play a new gamen";
cout << "Press X to exitnn";
cout << "--------------------------------------------------------------------------------" << endl;
cin >> newGameChoice;
newGameChoice = toupper(newGameChoice);
if (newGameChoice == 'N');
{
char userIn = 'a';
char c = 'a';
game(userIn, c);
}
while (newGameChoice != 'N' || 'X')
{
cout << "--------------------------------------------------------------------------------";
cout << "n Invalid input. Please try again.n" << endl;
cout << "--------------------------------------------------------------------------------" << endl;
newGame();
}
}
你的问题是:
if (begin != 'B');
{
...
cin >> begin;
begin = toupper(begin);
start(); <------
你再次调用start()
,它将再读取一个值到begin
。
在寻求帮助之前,请花更多的时间分析你的代码,这将帮助你成长为一个开发人员更多。
while (newGameChoice != 'N' || 'X')
等价于
while (newGameChoice != 'N' || 'X' != 0)
也许你的意思是
while (newGameChoice != 'N' || newGameChoice != 'X')
编辑:代码是错误的,必须重写,这里有一个建议:
void newGame()
{
char newGameChoice = 'a';
while (true) {
while (true) {
cin >> newGameChoice;
newGameChoice = toupper(newGameChoice);
if (newGameChoice != 'X' && newGameChoice != 'N') {
// Wrong input print error message
} else {
break;
}
}
if (newGameChoice == 'X') {
return;
}
game('a', 'a');
}
}
你的部分问题是你的start()
方法不是以最合乎逻辑的方式设计的。当前,当给出无效输入时,您将尝试读入另一个输入并再次调用start()
。当您第二次调用start()
时,它从start()
方法的开头开始,不知道之前的输入。
你应该做的是,当给出一个无效的输入时,使用while()
循环,直到输入正确的输入才继续。
void start()
{
...
//Get initial user input
while begin != 'B'
{
Keep getting input if wrong
}
game(userIn, c);
}
相关文章:
- 有没有办法提示用户使用哪种数据类型作为模板 c++
- 为什么 std::cin 不提示用户输入?
- 编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
- 为什么我的代码在 c++ 中无限循环.我的代码需要反复提示用户
- (显示金字塔)编写一个程序,该程序提示用户输入1到15的整数并显示金字塔
- 循环不提示用户输入(C )
- C++ 编写一个程序,提示用户以数字形式输入一个人的出生日期(投掷/接球)
- 提示用户填写链接列表
- 使用提示用户输入笛卡尔平面中某些点的x-y坐标(浮点类型)的函数
- 如何提示用户在C++中输入正确的电子邮件地址格式
- 提示用户输入,直到C++正确为止
- 安装盾,安装应用程序后,系统会提示用户安装程序
- qt检查文件中是否存在文件,如果它没有提示用户输入其位置,则将文件复制到程序工作目录
- 提示用户输入两个 3x3 int 数组并检查等效性
- 如果输入不是整数,则连续提示用户输入
- 是否可以提示用户输入并提供默认值
- 如何提示用户输入数字,直到他们选择奇数?C++
- 如何提示用户输入字符或数字
- 提示用户输入正数,并继续提示用户,直到他们输入正数 c++
- 如何使用 for 循环多次提示用户输入不同的文件名