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

时间:2015-05-30 20:10:23

标签: c++ while-loop

我正在编写一个代码,使用户能够确定三明治销售业务的利润。然而,我在使用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之外的任何数字。然而,当我编译时,编译器则相反。为什么会这样,解决方案是什么?

4 个答案:

答案 0 :(得分:3)

尝试以下

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.";

答案 1 :(得分:2)

只要表达式((sandwichtype > 0 && sandwichtype < 4))的计算结果为True,while循环就会重复。

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

答案 2 :(得分:2)

您将while条件反转 - 如果用户未输入有效数字,您希望打印该消息 - 这是任何不在间隔&lt; 1,3&gt;中的数字。

所以你必须否定自己的状况:

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

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

while (sandwichtype < 1 || sandwichtype > 3)

最后但并非最不重要的是,我建议接受整个阻止并缩进它。

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;
}

答案 3 :(得分:1)

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;
}