一旦满足条件,C ++就会停止while循环

时间:2013-01-21 00:50:46

标签: c++

do {
   cout << "Quantity  : ";
   cin >> sale->quantity;
   cout << "Unit Price: ";
   cin >> sale->unitPrice;
   cout << "Taxable   : ";
   cin >> sale->taxStatus;
} while (sale->quantity != 0); 

当我为0输入quantity时,它仍会询问我unitPricetaxStatus,然后它会终止。如果输入quantity 0,我怎么能让我的循环终止?

修改

> echo "" | a.out 
Sale Records 
=============
Quantity  : Unit Price: Taxable   : Quantity  : Unit Price: Taxable   : Quantity  : Unit Price: Taxable   : Quantity  : Unit Price: Taxable   : Quantity  : Unit Price: Taxable   : Quantity  : Unit Price: Taxable   : Quantity  : Unit Price: Taxable   : Quantity  : Unit Price: Taxable   : Quantity  : Unit Price: Taxable   : Quantity  : Unit Price: Taxable   : >

4 个答案:

答案 0 :(得分:5)

你有没有尝试告诉它在质量为0时终止?

cin >> sale->quantity;
if (sale->quantity == 0) break;

答案 1 :(得分:1)

您可以在cin >> sale->quantity;

之后添加此检查,以提前摆脱循环
if (sale->quantity == 0)
    break;

答案 2 :(得分:0)

一旦quantity输入为0,终止循环的一种方法是将该逻辑的其余部分放在if语句中。

另一种方法是使用break,但我会将循环更改为for(;;)

请注意,对于循环体末尾的do循环,每次循环迭代仅检查循环连续条件一次:它不会被连续检查。

答案 3 :(得分:0)

另一种选择是

cout << "Quantity  : ";
cin >> sale->quantity;
while (sale->quantity != 0)
{
   cout << "Unit Price: ";
   cin >> sale->unitPrice;
   cout << "Taxable   : ";
   cin >> sale->taxStatus;
   // next iteration for Quantity
   cout << "Quantity  : ";
   cin >> sale->quantity;
} 

但是我不确定你是否对每次迭代的销售结构做了什么。如果是这样,您需要在评论// next iteration for Quantity

之前添加该代码