C++While循环中断
C++ While Loop Break
我的目标是创建一个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)
中存在相同的错误。
相关文章:
- 我的代码运行良好,但在游戏循环中中断
- 使用 UDP 中断 while()-循环
- 如何使用中断停止循环?
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 使用 shared_ptr 在中断时结束多线程循环
- 为什么我的 while 循环对于特定输入中断,而对于其他输入工作正常?
- 为什么循环没有中断,并且 if 条件没有按预期工作?
- C 从另一个函数中断循环
- 使用 while(1) 但在 C++ 中无法中断循环
- 输入特定数字时中断循环
- 干净编码:如何从循环中的函数调用内部中断循环
- nullptr 不会在以零结尾的字符串上中断循环
- 使用 std::weak_ptr 和别名构造函数中断循环引用:声音或有问题
- 用功能中断循环
- g++优化中断循环
- 无法使用 cin.get 来检测周期来中断循环
- 返回内部循环以C++中断循环
- OpenMP 不支持中断循环
- while语句中断循环
- 如何在Linux应用程序上使用C++中的终端输入中断循环/进程