c++ - 货币选择有效,除非用户选择欧元或 'e'

标签 c++

我在 Stroustrup 的 PPP 第 2 版中做了一个尝试这个练习,该程序应该接受一个值,后跟一个表示货币的后缀。这应该换算成美元。以下代码适用于“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”,它工作正常,但我不明白为什么其他人即使没有空格也能工作。

最佳答案

6e 可以解释为格式错误的 double 科学记数法 (6e == 6e0 == 6 * pow(10,0) == 6),因此它被 cin >> amount 读取和 >> currency读取空字符串。

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

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

关于c++ - 货币选择有效,除非用户选择欧元或 'e',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31746256/

相关文章:

c++ - OpenCV:使用 cmake 时对 `cv::imread 的 undefined reference

c++ - 如何隐藏或禁用 WIX 安装程序中的取消按钮?

c++ - swig:使 C++ 对象可在 perl 中打印?

c++ - 参数既是指针又是引用?

c++ - goto 对 C++ 编译器优化的影响

c++ - 实例化和删除对象 C++

c++ - 添加两个 FBO (opengl) - 和闪电问题

c++ - MPI C 逐行发送矩阵到所有进程子进程 (MPI_COMM_SPAWN)

c++ - 嵌套模板类型的用户定义推导指南

c++ - 用于从 std::vector (或其他序列)读取的流语法?