首页 > 解决方案 > 使用函数调用退出 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;
}

标签: c++

解决方案


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";
}

推荐阅读