I'm trying to have a program loop, accepting input and producing output until the user enters "0" as the input.
The proble开发者_Go百科m 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?
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
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:
- You can use
break
to prematurely exit out of a loop. - Your while line should look like
while (cin >> amount && cin >> currency)
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.
精彩评论