2011-04-06 126 views
1

我試圖建立一個程序循環,接受輸入併產生輸出,直到用戶輸入「0」作爲輸入。用cin檢查輸入「0」(零)

的問題是,我的程序接受輸入兩個值,就像這樣:

cin >> amount >> currency; 

所以,我想有這樣一個while語句:

while (amount != 0 && currency != "") { 
    cin >> amount >> currency; 
    cout << "You entered " << amount << " " << currency << "\n"; 
} 

然而,while語句始終執行,即使我輸入0作爲輸入。

如何編寫程序,使得它接受兩個值作爲輸入,除非用戶輸入0,在這種情況下它終止?

+0

什麼是數量和貨幣的數據類型?因爲如果你將它們聲明爲'int',currency!=「」將是無效的! int與char相比... – Swanand 2011-04-06 04:10:49

回答

4

你可以使用不執行的&&右側事實上,如果左邊是假的:

#include <iostream> 
#include <string> 
int main() 
{ 
    int amount; 
    std::string currency; 
    while (std::cin >> amount && amount != 0 && std::cin >> currency) 
    { 
     std::cout << "You entered " << amount << " " << currency << "\n"; 
    } 
} 

試運行:https://ideone.com/MFd48

2

問題是,在您打印完消息後,您會在下一次迭代中檢查。你可能想要的是類似下面的僞代碼:

while successfully read amount and currency: 
    if amount and currency have values indicating that one should exit: 
     break out of the while loop 
    perform the action corresponding to amount and currency 

我將離開實際的代碼給你,因爲我懷疑這是功課,但這裏有一些提示:

  1. 你可以使用break過早退出循環。
  2. 你而行應該是while (cin >> amount && cin >> currency)
0

'currency'和'amount'的數據類型是什麼? 如果'amount'的類型是'char',那麼'0'的整數值將取決於編碼(對於ASCII爲48)。因此,當你調用'cout < < amount'時,你會看到'0',但是當你評估'amount!= 0'時,它會返回true而不是false。