2

I did one of the try this exercises in Stroustrup's PPP 2nd Edition and the program is supposed to accept a value followed by a suffix indicating the currency. This should be converted to dollars. The following code works for "15y" or "5p", but when I enter "6e" it gives me "Unknown currency".

constexpr double yen_per_dollar = 124.34;
constexpr double euro_per_dollar = 0.91;
constexpr double pound_per_dollar = 0.64;

/* 
    The program accepts xy as its input where
    x is the amount and y is its currency
    it converts this to dollars.
*/
double amount = 0;
char currency = 0;
cout << "Please enter an amount to be converted to USD\n"
     << "followed by its currency (y for yen, e for euro, p for pound):\n";
cin >> amount >> currency;

if (currency == 'y') // yen
    cout << amount << currency << " == " 
         << amount/yen_per_dollar << " USD.\n";
else if (currency == 'e') // euro
    cout << amount << currency << " == "
         << amount/euro_per_dollar << " USD.\n";
else if (currency == 'p') // pound
    cout << amount << currency << " == "
         << amount/pound_per_dollar << " USD.\n";
else
    cout << "Unknown currency.\n";

If I type "6 e" instead it works fine but I don't understand why the others work even without space.

London
  • 65
  • 3
  • My best guess is that it thinks you are trying to read scientific notation. Try using this: cin >> std::fixed >> amount >> currency; – Radon Jul 31 '15 at 12:38
  • 1
    oh apparently according to this thread http://stackoverflow.com/questions/29656640/how-to-use-fixed-floatfield-for-istream-istringstream std::fixed is not for input streams and there's no easy way to prevent it from reading e – London Jul 31 '15 at 12:50

1 Answers1

1

6e can be interpreted as malformed scientific notation of double (6e == 6e0 == 6 * pow(10,0) == 6) so it gets read by cin >> amount and >> currency reads empty string.

try cin >> std::fixed >> amount (from <iomanip>) to force only 'normal' notation. if that doesn't help (and it probably wont on most compilers) - you will have to read line (std::getline()) and parse it manually (split on first non digit/dit or read from end etc.)

see also: How to make C++ cout not use scientific notation

Community
  • 1
  • 1
Hcorg
  • 11,598
  • 3
  • 31
  • 36
  • Adding std::fixed didn't work, but when i enter "6e0 e" the program works fine. "6e e" didn't though, maybe because there isn't a value after e. – London Jul 31 '15 at 12:43
  • I hoped it might work.. but apparently std::fixed is only for output. Unfortunately it will required by hand parsing... – Hcorg Jul 31 '15 at 12:55