如何提示用户在switch语句的default部分输入其他内容C++ [duplicate]

lb3vh1jj  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(151)
    • 此问题在此处已有答案**:

Good input validation loop using cin - C++(4个答案)
23小时前关门了。
在switch语句的末尾,我想提示用户输入另一个将在switch语句中再次检查的输入。如何将新的用户输入重新循环到switch语句中?

switch(choice){
        case 'l' :
            ct.Start();
            count = LinearSearch(new_books, requested_books); 
            ct.Stop();
            break;
        case 'b' :
            ct.Start(); 
            Sort(new_books, requested_books); 
            count = BinarySearch(new_books, requested_books); 
            ct.Stop();
            break;
        case 'r' :
            ct.Start();
            Sort(new_books, requested_books); 
            count = RecursiveBinarySearch(new_books, requested_books); 
            ct.Stop();
            break;
        default : 
            std::cout << "Incorrect choice\n";
            std::cout << "Choice of search method ([l]inear, [b]inary, [r]recursiveBinary)?";
            std::cin >> choice;  //do I need to run some sort of while loop here?
    }

我想我必须将switch语句 Package 在while循环中,但我不知道它将如何工作

8gsdolmq

8gsdolmq1#

你说得对,需要一个循环。试试看:

bool promptAgain;

do {
    std::cout << "Choice of search method ([l]inear, [b]inary, [r]recursiveBinary)?";
    std::cin >> choice;

    promptAgain = false;

    switch (choice){
        case 'l' :
            ct.Start();
            count = LinearSearch(new_books, requested_books); 
            ct.Stop();
            break;
        case 'b' :
            ct.Start(); 
            Sort(new_books, requested_books); 
            count = BinarySearch(new_books, requested_books); 
            ct.Stop();
            break;
        case 'r' :
            ct.Start();
            Sort(new_books, requested_books); 
            count = RecursiveBinarySearch(new_books, requested_books); 
            ct.Stop();
            break;
        default : 
            std::cout << "Incorrect choice\n";
            promptAgain = true;
            break;
    }
}
while (promptAgain);

相关问题