我正在编写一个代码,使用户能够确定三明治销售业务的利润。但是,我在使用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;
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.";
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句