rottendevice
rottendevice

Reputation: 2879

Checking for input "0" (zero) with cin

I'm trying to have a program loop, accepting input and producing output until the user enters "0" as the input.

The problem is, my program accepts two values for input, like this:

cin >> amount >> currency;

So, I tried to have a while statement like this:

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

However, the while statement always executes, even if I enter 0 as input.

How do I write the program such that it accepts two values as input except when the user enters 0, in which case it terminates?

Upvotes: 1

Views: 5906

Answers (3)

bancsy
bancsy

Reputation: 142

What are the data types of 'currency' and 'amount'? If 'amount' is of type 'char' then its integer value for '0' would be something else depending on the encoding ( 48 for ASCII ). Thus when you call 'cout << amount' you see '0' but when you evaluate 'amount != 0' it returns true instead of false.

Upvotes: 0

Cubbi
Cubbi

Reputation: 47418

You could use the fact that the right side of && is not executed if the left is false:

#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";
    }
}

test run: https://ideone.com/MFd48

Upvotes: 5

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95479

The problem is that you do your check on the next iteration, after you've already printed the message. What you probably want is something like the following pseudo-code:

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

I'll leave the actual code to you, since I suspect this is homework, however here are some hints:

  1. You can use break to prematurely exit out of a loop.
  2. Your while line should look like while (cin >> amount && cin >> currency)

Upvotes: 2

Related Questions