C++中while()循环的不理解

Incomprehension of the while() loop in C++

我正在编写一个代码,使用户能够确定三明治销售业务的利润。然而,我在使用 while() 时遇到问题。

int sandwichtype=1;

cout << "Enter the type of sandwich" << endl
     << "Input 1 for cheese, 2 for veggie, 3 for customed" << endl << endl
     << "Sandwich type: ";

while (sandwichtype > 0 && sandwichtype < 4)
cin >> sandwichtype;

我想要的是限制用户输入除 1、2 或 3 之外的任何数字。然而,当我编译时,编译器执行相反的操作。为什么会这样,解决方法是什么?

int sandwichtype=0;

while (sandwichtype < 1 || sandwichtype > 3) {
    cout << "Enter the type of sandwich" << endl
         << "Input 1 for cheese, 2 for veggie, 3 for customed" << endl << endl
         << "Sandwich type: ";
    cin >> sandwichtype;
}

尝试以下方法

int sandwichtype;

do
{
    cout << "Enter the type of sandwich" << endl
         << "Input 1 for cheese, 2 for veggie, 3 for customed" << endl << endl
         << "Sandwich type: ";
    cin >> sandwichtype;
} while ( sandwichtype < 1 || sandwichtype > 3 );

至于你的 while 语句

while (sandwichtype > 0 && sandwichtype < 4)
cin >> sandwichtype;

当用户输入有效选择时迭代并在用户输入无效选择时停止迭代。

另外你应该检查用户没有中断输入。例如

do
{
    cout << "Enter the type of sandwich" << endl
         << "Input 1 for cheese, 2 for veggie, 3 for customed" << endl << endl
         << "Sandwich type: ";

    sandwichtype = 0;
} while ( cin >> sandwichtype && ( sandwichtype < 1 || sandwichtype > 3 ) );


if ( sandwichtype == 0 ) cout << "Oops! The user does not want to contact.";

只要其表达式 ((sandwichtype > 0 && sandwichtype < 4)) 的计算结果为 True.

,while 循环就会重复

这意味着,只要值为>0<4,它就会重新读取用户的数据。 只有当用户输入超出此范围的值(根据您的定义是无效数据)时,while 循环才会停止,程序将继续(并处理无效数据)。

您将 while 条件反转 - 如果用户未输入有效数字 - 您想要打印该消息 - 这是不在区间 <1,3> 中的任何数字。

所以你必须否定你的条件:

while (!(sandwichtype > 0 && sandwichtype < 4))

它可能会被重写为可能更容易阅读

while (sandwichtype < 1 || sandwichtype > 3)

最后但同样重要的是,我建议包含整个 while 块并缩进它。

int sandwichtype = 0;
cin >> sandwichtype;
while (sandwichtype < 1 || sandwichtype > 3)
{   
    cout << "Enter the type of sandwich" << endl
        << "Input 1 for cheese, 2 for veggie, 3 for customed" << endl << endl
        << "Sandwich type: ";

    cin >> sandwichtype;
}