为什么循环不中断?

问题描述 投票:0回答:1

我编写了这个简单的菜单,直到我选择退出为止。每个选择功能仅显示已选择的消息。每个函数都放置在while(true)循环中的switch语句中。它应该在函数运行一次后中断,但是我遇到了无限循环。我已经尝试了其他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;
}





c++ loops menu infinite
1个回答
0
投票

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

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

如果要只运行一次,则完全删除while循环。


0
投票

请注意,break内部的switch仅会破坏开关,不会破坏整个while循环!

switch语句在执行测试用例后中断,但循环继续进行,因为它的条件是true,并且在return中的case 8之外,没有其他break或return语句。只有这样,您的代码才能正常工作。

我已经用else if语句尝试过,并且工作正常。

这是因为在这种情况下,break将破坏您的while循环,而不是像switch语句那样破坏case

解决方案:

完全删除while循环,并只保留其中的内容。您在那里不需要循环,实际的循环发生在菜单内部(即do-while循环)。另外,为每种情况添加适当的return语句。当前,只有case 8具有return语句。

© www.soinside.com 2019 - 2024. All rights reserved.