不使用break退出do/while循环
Exiting do/while loop without using a break
我有一个学校的问题,它是这样工作的:
用户可以输入的字符串是电话号码或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;
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- while循环中while循环的时间复杂度是多少
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 擦除while循环中迭代的元素
- 为什么我不能在 while 循环中创建线程?
- 退出简单while循环时出现问题
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 嵌套While循环不起作用(C++问题)
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 使用 GMP 的 while 循环出现问题
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么在 while 循环中返回表达式不起作用
- 如何使用 do while 循环确定最高值和最低值
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- OpenCV QT,显示视频的帧(不使用while循环)
- 在 while 循环中使用 pow() 函数 C++
- C++ 制作/命名不初始化的向量(在 while 循环中)
- std::getline没有在while循环中重新请求用户输入