在 C++ 中的货币之间转换的程序中出现问题

Trouble in a program to convert between currencies in C++

我用 C++ 编写了一个简单的程序来在货币之间进行转换,作为课程的一部分。它要求输入一个数值,然后输入一个字母(y、e 或 p)来表示一种受支持的货币。使用 'y' 或 'p' 时,您可以将数值和字符一起输入或用 space 分隔(即:“100y”或“100 y”),它会正常工作。但是,仅对于字母 'e',如果我同时输入这两个字母,则它不会被识别为有效输入。有人知道为什么吗?

代码如下:

#include <iostream>

int main()
{
using namespace std;
constexpr double yen_to_dollar = 0.0081;    // number of yens in a dollar
constexpr double euro_to_dollar = 1.09;     // number of euros in a dollar
constexpr double pound_to_dollar = 1.54;    // number of pounds in a dollar

double money = 0;                           // amount of money on target currency
char currency = 0;
cout << "Please enter a quantity followed by a currency (y, e or p): " << endl;
cin >> money >> currency;

if(currency == 'y')
    cout << money << "yen == " << yen_to_dollar*money << "dollars." << endl;
else if(currency == 'e')
    cout << money << "euros == " << money*euro_to_dollar << "dollars." << endl;
else if(currency == 'p')
    cout << money << "pounds == " << money*pound_to_dollar << "dollars." << endl;
else
    cout << "Sorry, currency " << currency << " not supported." << endl;

return 0;
}

当您输入 100e10e 时,它工作正常。 100e10 是科学计数法中的有效数字。 100e 不是科学记数法中的有效数字。它不转换为 double 并且 money 被赋值为 0。变量 currency 保持不变。这就是您收到 "Sorry, currency not supported" 消息的原因。 e在本例中属于一个数字,因为它符合科学计数格式。

您可以为每种货币分配 4 个字符(例如 _EUR)。它将解决问题并且更加用户友好。