2011-04-06 67 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。