用cin检查输入“0”(零)

时间:2011-04-06 03:55:54

标签: c++

我正在尝试一个程序循环,接受输入并产生输出,直到用户输入“0”作为输入。

问题是,我的程序接受两个输入值,如下所示:

cin >> amount >> currency;

所以,我尝试了这样的while语句:

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

但是,即使我输入0作为输入,while语句也会始终执行。

如何编写程序,使其接受两个值作为输入,除非用户输入0,在这种情况下它会终止?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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行应该看起来像while (cin >> amount && cin >> currency)

答案 2 :(得分:0)

'货币'和'金额'的数据类型是什么? 如果'amount'的类型为'char',那么'0'的整数值将取决于编码(对于ASCII为48)。因此当你打电话给'cout&lt;&lt;金额'你看'0',但是当你评价'金额!= 0'时,它会返回true而不是false。

相关问题