Reputation: 45
I've made a simple program in C++ to convert between currencies, as part of a lesson. It asks for a numerical value and then a letter (y, e or p) to represent one of the supported currencies. When using 'y' or 'p' you can input the numerical value and character together or separated by a space (ie: "100y" or "100 y") and it'll work fine. However, for the letter 'e' only, if I enter both together, it doesn't recognize as a valid input. Does anyone have any idea why?
Here's the code:
#include <iostream>
int main()
{
using namespace std;
constexpr double yen_to_dollar = 0.0081; // number of yens in a dollar
constexpr double euro_to_dollar = 1.09; // number of euros in a dollar
constexpr double pound_to_dollar = 1.54; // number of pounds in a dollar
double money = 0; // amount of money on target currency
char currency = 0;
cout << "Please enter a quantity followed by a currency (y, e or p): " << endl;
cin >> money >> currency;
if(currency == 'y')
cout << money << "yen == " << yen_to_dollar*money << "dollars." << endl;
else if(currency == 'e')
cout << money << "euros == " << money*euro_to_dollar << "dollars." << endl;
else if(currency == 'p')
cout << money << "pounds == " << money*pound_to_dollar << "dollars." << endl;
else
cout << "Sorry, currency " << currency << " not supported." << endl;
return 0;
}
Upvotes: 2
Views: 591
Reputation: 9595
When you enter 100e10e
it works ok. 100e10
is a valid number in scientific notation. 100e
is not a valid number in scientific notation. It is not converted to double
and money
is assigned 0. Variable currency
stays unchanged. That is why you get "Sorry, currency not supported" message. e
belongs to a number in this case, because it fits scientific notation format.
You could assign 4 chars to every currency( _EUR for instance ) . It would solve the problem and be more user friendly.
Upvotes: 2