gpt4 book ai didi

c++ - 在C++中输入无效时再次提示

转载 作者:行者123 更新时间:2023-12-02 10:18:08 25 4
gpt4 key购买 nike

我知道这可能是一个非常基本的问题,但是我很困惑。我试图提示用户输入1、2、3或4。而且,如果他们没有输入有效的选择,请再次询问他们。但是,每当我执行程序并输入无效的结果时,它就会循环播放而不会停止供用户输入,一遍又一遍地打印第一条提示行。我怎样才能解决这个问题?从内部调用函数是个坏主意吗?我需要以某种方式清除cin吗?

int hallwayask()
{
int input;
cout << "1: Door 1 \n2: Door 2 \n3: Door 3 \n4: Door 4\n";
cin >> input;
if (cin.good())
{
switch(input)
{
case 1:
room1();
break;
case 2:
room2();
break;
case 3:
room3();
break;
case 4:
room4();
break;
default:
cout << "Please enter a valid number." << endl;
break;
}
}
else
{
hallwayask();
}
}

最佳答案

试试这个片段。这是不言自明的,而且您不必一次又一次调用该函数,从而使逻辑更容易且程序更快。

int hallwayask()
{
int input;

//Write the "do{" here if you wish these
//options to be shown again and again when
//user gives invalid input

cout << "1: Door 1 \n2: Door 2 \n3: Door 3 \n4: Door 4\n";

do
{ //this is the "do{" I referred to earlier
cin >> input;

switch (input)
{

case 1:
room1();
break;

case 2:
room2();
break;

case 3:
room3();
break;

case 4:
room4();
break;

default:
cout << "Please enter a valid number: " << endl;
break;
}
} while ((input != 1) && (input != 2) && (input != 3) && (input != 4));

return (input); //the correct input is returned to the calling function

}

关于您的问题-不,只要您知道调用链将终止于某个点,从自身调用相同的函数(我们称为“递归调用”)就不错。一个非常常见的示例是用于查找整数阶乘的递归算法。在这种情况下,我们不使用可能无法到达终点的递归函数;如果用户继续输入错误该怎么办?您只需要填满堆栈,如果内存满了就会崩溃。 (因为每个递归函数调用将函数的当前实例压入堆栈)

关于c++ - 在C++中输入无效时再次提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61260185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com