Reputation: 569
I am doing an exercise on currency exchange. Program should read amount and name of currency form input stream and return its value in national currency.
double amount = 0.0;
std::string currency = " ";
std::cout << "Please enter amount and currency ('usd','eur' or 'rub'):" << std::endl;
std::cin >> amount >> currency;
std::cout << amount << currency << std::endl;
if ( currency == "usd") {
...;
} else if ( currency == "eur" ) {
...;
} else if ( currency == "rub" ) {
...;
} else {
std::cout << "Input error: unknown currency..." << std::endl;
}
I've encountered a weird problem with std::cin in this program. When typing in "100usd" or "100rub" the program echoes "100usd" or "100rub" respectively and continues to work normally. But when I type "100eur" it echoes "0" and gives out the "Input error..." line. At the same time, should I type "100 eur", the program echoes "100eur" and works fine. In first two cases it makes no difference if I put whitespace or not.
What am I doing wrong?
Upvotes: 2
Views: 1941
Reputation: 15916
In the 100eur case it thinks you're trying to write a double in scientific notation: 1.0e-10
but fails to parse the rest of it (because ur is not valid for the exponent "section").
In the other cases it stops at 100 (when it reaches u/r) which is valid for a double so the parse succeeds.
Upvotes: 5