为什么循环不中断?

用户名

我写了这个简单的菜单,直到我选择退出为止。每个选择功能仅显示已选择的消息。每个函数都放置在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;
}





克里斯·MM

您不需要在内部输入新的输入while (true),因此return除非最初给出声明,否则它将永远不会达到该声明8要解决此问题,只需testChoice在循环内更新变量。可能的解决方案是:

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章