c++ - 为什么我的 do-while 循环不继续循环?

标签 c++ do-while

我正在努力创建一个带有错误检查的菜单,这是我想出的,但我似乎无法让它工作。

#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 测试为 bool 值,这意味着 0 为 FALSE,非 0 为 TRUE。因此,一旦 while 中的条件被评估为 FALSE,循环就结束了。

关于c++ - 为什么我的 do-while 循环不继续循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32916734/

相关文章:

c++ - C++ 中并行 vector 的 find_first

c++ - 我可以将堆大小设置为 0 吗?

c++ - 我需要线程函数在不停止实际程序的情况下每 2 秒打印一次随机数

c - 在函数中切换 do..while 循环的最佳方法?

c++ - fflush - 如何检查最后一个操作是否为输出操作

c++ - boost 多索引 : lower_bound with value_type as argument

c++ - 读出一个大的txt文件

java while 循环计数不正确

javascript - 斐波那契数列 Javascript 执行 while 循环

java - 函数不执行 do-while 循环...不返回 main?