c++ - 使用函数调用退出 While 循环
问题描述
我有一个类似于下面的循环,我已经看过了,有人知道吗?我已经想到,必须在循环本身中使用一个 break 语句,但是有什么可能的方法可以从函数调用中退出 while 循环,因为我似乎找不到任何方法,有可能还是我只是去改用while循环。
#include <iostream>
using namespace std;
int someinput=1;
int state=2;
void ifcondtionismetbreak(int x){
if (x == 1)
{
// EXIT WHILE LOOP SOLUTION
}
else
{
cout <<"Continue";
}
}
int main() {
while (state==2){
cout << "This was Printed\n";
ifcondtionismetbreak(someinput);
cout << "Don't Print This When Condition Wants to Exit Loop\n";
}
return 0;
}
解决方案
break
使用语句从函数内直接跳出循环是不可能的。你可以bool
从你的函数中返回
bool ifcondtionismetbreak(int x) {
if (x == 1)
return true;
return false;
}
并在循环中查询此返回值:
while (state == 2) {
if (ifcondtionismetbreak(someinput))
break;
cout << "Don't Print This When Condition Wants to Exit Loop\n";
}
推荐阅读
- excel - (不是文本到列) - 用分隔符将 1 列分成许多列
- reactjs - 使用 react-pdf (@react-pdf/renderer) 在浏览器中以模式从 blob 数据显示 PDF
- javascript - 反应 onChange 不适用于功能组件内的输入
- raspberry-pi - Raspbery Pi Pico 未连接到 PC /Raspberry Pi 4
- r - 如何确定每个人的最大数字跨度?
- python - 如何使“导入日期时间”仅显示一天
- python - 计算半正定矩阵的矩阵幂和矩阵指数的最准确方法
- python - 单击按钮后,Tkinter 中的语音识别没有响应
- c++ - 将值分配给数组时出现分段错误错误
- flutter - Flutter with Firebase 没有在 foreach 循环中更新我的列表