为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?

Why is my do-while loop not breaking when I enter a number that is accepted?

本文关键字:我的 数字 do-while 循环 中断 输入 一个 为什么      更新时间:2023-10-16

无论我输入接受还是不接受的值,循环都会继续运行。

#include <iostream>
#include <vector>
using namespace std;
int main(){
int size;
bool accepted = ((size == 0) || (size == 3) || (size == 4) || (size == 5));
/************************************************************************/
do {
cout << "Enter number of digits in code (3, 4 or 5): " << flush;
cin >> size;
} while (!accepted);
/************************************************************************/
//static_cast<const int>(size);
cout << size;
return 0;
}

布尔值不会每次迭代都会更新。仅在开始时。要使逻辑工作,您需要将

accepted = ((size == 0) || (size == 3) || (size == 4) || (size == 5));

循环内部。

int main(){
int size;
bool accepted;
/************************************************************************/
do {
cout << "Enter number of digits in code (3, 4 or 5): " << flush;
cin >> size;
accepted = ((size == 0) || (size == 3) || (size == 4) || (size == 5));
} while (!accepted);
/************************************************************************/
//static_cast<const int>(size);
cout << size;
return 0;
}
相关文章: