2012-07-15 93 views
2

我在代码中有一个问题在循环中出现。如果用户完成输入项目,我希望他们按q退出。这不起作用,q被用户输入并且循环没有被破坏。如果还有更好的方法来做到这一点,那就太好了。如果字符串不等于const char break while while循环

#include <stdio.h> 
#include "CashRegister.h" 
#include <stdlib.h> 
#include <iostream> 
#include <string> 
using namespace std; 

CashRegister::CashRegister(void) 
{ 
} 

CashRegister::~CashRegister(void) 
{ 
} 

void CashRegister::addItem(void) 
{ 
string temp; 
int k = 0; 
int exit = 0; 
CashRegister item[10]; 

for(int i = 0; i < 10; ++ i) 
{ 
    item[i].price = 0.00; 
} 

cout << "Enter price of items. Up to 10 maximum\n" << endl; 

while(item[9].price != 0.00 || temp != "q") 
{ 
    cout << "Enter price of item number " << k + 1 << "\n" << endl; 
    cin >> temp; 
    cout << temp << endl; 
    double tempPrice = (double)atof(temp.c_str()); 
    item[k].price = tempPrice; 
    cout << "Price of item number " << k + 1 << " is $" << item[k].price << endl; 
    ++k; 
} 

}

回答

4

while循环需要阅读:

while(item[9].price != 0.00 && temp != "q") 

循环需要继续,而这两个条件都满足,那么你需要说&&||

+0

对不起按偏,我的循环似乎就要结束现在过早。 – user1527216 2012-07-15 18:12:20

+0

嗯,是'item [9] .price' ever'0.00'?这似乎是会发生的唯一原因。 – WendiKidd 2012-07-15 18:21:29

+0

当我做if语句来检查它是否为0.00时,它确实为0.00。我只是将我的代码更改为'while(item [9] .price <= 0.00)',现在一切正常。 – user1527216 2012-07-15 18:48:45

2
while(item[9].price != 0.00 || temp != "q") 

想想这是什么话。 “Loop while price is not 0 or temp is not”q“。”现在考虑一下为什么停止循环。

0

您应该使用它来打破循环:

while(item[9].price != 0.00 && temp != "q") 
{ 
    // ur stuff 
} 

循环会遍历因为项目[9]。价格将包含一些其他的值,那么0.00