C++While循环中断

C++ While Loop Break

本文关键字:中断 循环 C++While      更新时间:2023-10-16

我的目标是创建一个C++程序,该程序重复执行一段代码,直到用户输入一个合适的值,并使用while循环。我的代码只是一遍又一遍地重复,即使我输入了"0",它仍然会重复循环中的代码块。

这是我的源代码:

#include <iostream>
using namespace std;
int main()
{
    int num = 0;
    bool repeat = true;
    while (repeat = true)
    {
        cout << "Please select an option." << endl;
        cout << "[1] Continue Program" << endl;
        cout << "[0] Terminate Program" << endl;
        cout << "---------------------" << endl;
        repeat = false;
        cin >> num;
        cout << endl;
        if (num = 1)
        {
            repeat = true;
            //execute program
        }
        else if (num = 0)
            repeat = false;
        else
            cout << "Please enter an appropriate value.";
    }
    return 0;
}
  while (repeat = true)
                ^^

是你的问题之一:

  while (repeat == true)
                ^^

对于赋值,条件的计算结果总是为true。

有些人主张使用Yoda条件来避免这些拼写错误。另一种方法是简单地编译具有最高警告级别的程序:

-Wall

检查您的运算符。您在while和if参数中使用的是赋值运算符=,而不是比较运算符==

while (repeat = true)

while条件下,您使用的是赋值运算符=,而不是相等的==

它是有效的C++语法,但不是您所期望的。repeat被分配给true,因此条件总是成立的。

if (num = 1)else if (num = 0)中存在相同的错误。