gpt4 book ai didi

c++ - 为什么循环不中断?

转载 作者:行者123 更新时间:2023-12-01 15:13:20 25 4
gpt4 key购买 nike

我写了这个简单的菜单,直到我选择退出为止。每个选择功能仅显示已选择的消息。每个函数都放置在while(true)循环中的switch语句中。它应该在函数运行一次后中断,但是我遇到了无限循环。我已经用else if语句尝试过,并且工作正常。我要使用开关,因为它看起来很干净并且易于管理。请告诉我逻辑错误,我将修复它。

#include <iostream>
#include <limits>


bool validation(int testChoice, int minC, int maxC, std::string message)
{
bool invalid = false;

if ((std::cin.fail())|| (testChoice >maxC) || (testChoice < minC))
{
std::cout << message <<std::endl;
invalid = true;
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
}
return invalid;
}

int menu()
{
bool flag = true;
int testChoice;
int minC = 1, maxC = 8;
do
{
std::cout <<"Which test to run?: \n";
std::cout <<"1. Test1 \n";
std::cout <<"2. Test2 \n";
std::cout <<"3. Test3 \n";
std::cout <<"4. Test4 \n";
std::cout <<"5. Test5 \n";
std::cout <<"6. Test6 \n";
std::cout <<"7. test7 \n";
std::cout <<"8. Quit \n";
std::cout <<"Pick one: ";
std::string message = "1-8 only: ";
std::cin >> testChoice;
flag = validation(testChoice, minC, maxC, message);
}
while(flag);
return testChoice;
}
void test1()
{
std::cout <<"Test 1 was chosen\n";
}
void test2()
{
std::cout <<"Test 2 was chosen\n";
}
void test3()
{
std::cout <<"Test 3 was chosen\n";
}
void test4()
{
std::cout <<"Test 4 was chosen\n";
}
void test5()
{
std::cout <<"Test 5 was chosen\n";
}
void test6()
{
std::cout <<"Test 6 was chosen\n";
}
void test7()
{
std::cout <<"Test 7 was chosen\n";
}
int toRun(int testChoice) //Pass in the return value from menu
{
while (true)
{

switch(testChoice)
{
case 1:
test1();
break;

case 2:
test2();
break;

case 3:
test3();
break;

case 4:
test4();
break;

case 5:
test5();
break;

case 6:
test6();
break;

case 7:
test7();
break;
case 8:
return 0;

}
}
}
int main ()
{
int choice = menu();
toRun(choice);
return 0;
}





最佳答案

您不需要在while (true)内要求新的输入,因此除非最初为其指定return,否则它将永远不会击中8语句。要解决此问题,只需在循环内更新testChoice变量。可能的解决方案是:

int toRun() // No parameter needed now
{
while (true)
{
int testChoice = menu();
switch(testChoice)
{


如果您希望它只运行一次,则完全删除 while循环。

关于c++ - 为什么循环不中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61050422/

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