2
votes

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?

1
Thats because you can write a double in scientific notation (which involves the letter e) but the rest of the letters in eur are invalid for this so the parsing fails. - Borgleader
This is (among others) why you don't use std::istream::operator>> but rather std::getline and then parse the input yourself. Also, don't use floating-point numbers for money since it's inexact. - The Paramagnetic Croissant
@TheParamagneticCroissant: "don't use floating-point numbers for money" - why not? It's only a problem if you're processing real transactions, or have some other reason to require an exact representation. - Mike Seymour

1 Answers

5
votes

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.