【问题标题】:Currency selection works except when user selects euro or 'e'货币选择有效,除非用户选择欧元或“e”
【发布时间】:2015-10-23 03:18:33
【问题描述】:

我在 Stroustrup 的 PPP 2nd Edition 中做了一个尝试这个练习,该程序应该接受一个值,后跟一个表示货币的后缀。这应该转换为美元。以下代码适用于“15y”或“5p”,但当我输入“6e”时,它会显示“未知货币”。

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";

如果我输入“6 e”,它可以正常工作,但我不明白为什么其他人即使没有空格也可以工作。

【问题讨论】:

  • 我最好的猜测是它认为您正在尝试阅读科学记数法。试试这个:cin >> std::fixed >> amount >> currency;
  • 哦,显然根据这个线程stackoverflow.com/questions/29656640/… std::fixed 不适用于输入流,并且没有简单的方法可以防止它读取 e

标签: c++


【解决方案1】:

6e 可以被解释为双精度格式错误的科学记数法 (6e == 6e0 == 6 * pow(10,0) == 6),因此它会被cin &gt;&gt; amount 读取,而&gt;&gt; currency 读取的是空字符串。

尝试cin &gt;&gt; std::fixed &gt;&gt; amount(来自&lt;iomanip&gt;)仅强制使用“正常”表示法。如果这没有帮助(并且它可能不会在大多数编译器上) - 你将不得不阅读行(std::getline())并手动解析它(拆分第一个非数字/dit或从末尾读取等)

另请参阅:How to make C++ cout not use scientific notation

【讨论】:

  • 添加 std::fixed 不起作用,但是当我输入“6e0 e”时,程序运行正常。 "6e e" 没有,可能是因为 e 后面没有值。
  • 我希望它可以工作.. 但显然 std::fixed 仅用于输出。不幸的是,它需要手动解析...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
  • 2018-10-29
  • 2023-03-15
相关资源
最近更新 更多