为什么我的同时循环不会继续循环?
Why won't my do-while loop continue looping?
我正在创建一个带有错误检查的菜单,这就是我想出来的,但是我似乎不能让它工作。
#include <iostream>
using namespace std;
int main()
{
char option; // user's entered option will be saved in this variable
int error1 = 0;
//Displaying Options for the menu
cout << "There are three packages available." << endl;
cout << "Monthly Price - Price per MB for overages (excluding C)" << endl;
cout << "A) $15 - $.06 for each MB after 200 MB." << endl;
cout << "B) $25 - $.02 for each MB after 2,000 MB ( approx. 2 GB)." << endl;
cout << "C) $50 - Unlimited data." << endl;
do //do-while loop starts here
{
//Prompting user to enter an option according to menu
cout << "Please enter which plan you currently have : ";
cin >> option; // taking option value as input and saving in variable "option"
if(option == 'A' || option == 'a') // Checking if user selected option 1
{
cout << "You chose a" << endl;
error1 = 1;
}
else if(option == 'B' || option == 'b') // Checking if user selected option 2
{
cout << "You chose b" << endl;
error1 = 1;
}
else if(option == 'C' || option == 'c') // Checking if user selected option 3
{
cout << "You chose c" << endl;
error1 = 1;
}
else //if user has entered invalid choice
{
//Displaying error message
error1 = 0;
cout << "Invalid Option entered";
}
}
while(error1 = 0); //condition of do-while loop
return 0;
}
当输入错误的值时,输出将是Invalid Option entered;但是,它不会循环回到开头并提示用户再次输入。
它为什么这样做?
变化
while(error1 = 0); //condition of do-while loop
到
while(error1 == 0); //condition of do-while loop
在第一个选项中,您只是将0分配给error1
,然后error1
被测试为布尔值,这意味着0为FALSE,非0为TRUE。因此,一旦while
中的条件被评估为FALSE,循环结束。
您将0
分配给while
中的error1
,这始终为假,因此循环不会重复。修改while(error1=0);
为while(error1==0);
就像补充一样:考虑将表达式反转如下:
while (0 = error1);
通过这种方式,如果您忘记了额外的=
或将赋值与相等操作符
相关文章:
- 循环后如何继续阅读
- 循环不继续无法弄清楚为什么
- 如何创建一个 while 循环,继续循环,直到在C++中输入'using streams'键?
- while 循环 C++ 结束,但不继续到其余语句
- While循环在fork和execvp调用后没有继续
- C++,程序输出无效输入,但继续通过循环
- 程序终止,而不是继续整数输入验证循环
- C /QT 5 Gstreamer继续循环
- 我如何摆脱循环并继续循环
- 在 fork() 之后,如何在 for() 循环中继续运行 execve()
- 如何在嵌套的 for 循环中使用“继续一段时间”循环
- C++ for 循环继续循环,即使它不应该循环
- 如何在无效的数据类型输入后继续循环
- 使用ifstreamwhile循环,如何显示输入错误并在下一行继续
- 在基于范围的 for 循环中继续不会重新触发断点?
- 有人可以帮助我做一个时循环,以便在每次计算后我都可以继续使用CIN值
- C++ ? 运算符,在 for 循环中继续运算符
- C++循环在 EOF 之后继续运行时这样做
- 在C++中添加while循环以继续或退出控制台
- 循环浏览文件夹中的所有文件以继续执行脚本