不使用break退出do/while循环

Exiting do/while loop without using a break

本文关键字:while 循环 do 退出 break      更新时间:2023-10-16

我有一个学校的问题,它是这样工作的:

用户可以输入的字符串是电话号码或X(如果他们想退出)。内部循环充满了检查电话号码并确保其长度和格式正确的函数,如果检测到错误,则提示用户再次输入,等等。

只要我输入电话号码,这段代码就可以正常工作。当我输入X时,它将X识别为需要进入内部循环以检查长度和格式的东西,而不仅仅是退出。

我已经尝试了许多不同的方法来解决这个问题,我唯一能得到的是break声明,我的教授不接受。

我怎么能写这个do/while循环不使用break ?我在初始选择提示符下面放置了一个cout语句,它显示输入了X,但如果不使用:

,它仍然不会退出:
if(selection == "x" || selection == "X")
    break;

相反,它将X发送到do/while循环中以将格式纠正为数字###-###-####:

string selection;
do
{   
    cout << "Please select a number from the list or type 'X' to exit:  ";
    cin >> selection;
    cout << endl;
    //if(selection == "x" || selection == "X")
    //break;
    if(selection != "x" || selection != "X")
        do
        {
            checking length function
            .
            .
            .
            checking format function
        } while(argument is true);
    resultFunc(prints the phone number + billing info from the parallel array);
} while(selection != "x" || selection != "X");
if(selection != "x" || selection != "X")

必须是:

if(selection != "x" && selection != "X")

这是德摩根定律的一个经典例子。您想知道selection是否为"x""x",因此相反的情况是,如果selection不是"x"不是"x"

首先,您需要正确地编写测试:

while(selection != "x" && selection != "X");

第二,不是做这个测试两次,而是只做一次,并将结果存储在布尔值中:

bool exitLoop = false;
do
{   
    cout << "Please select a number from the list or type 'X' to exit:  ";
    cin >> selection;
    cout << endl;
    if (selection == "x" || selection == "X")
        exitLoop = true;
    if ( !exitLoop )
    {
       // do stuff because input isn't X
    }
} while (!exitLoop);

布尔值exitLoop明确了是什么导致循环终止,而不是在多个地方对"X"进行重复测试。

此外,您可以使用toupper函数来代替检查上下"X":

    #include <cctype>
    //...
    if (std::toupper(selection[0]) == "X" )
        exitLoop = true;