我在Stroustrup的PPP第二版中尝试了这个练习之一,该程序应该接受一个值后跟一个表示货币的后缀。这应该转换成美元。以下代码适用于" 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";
如果我输入&#34; 6 e&#34;相反,它工作正常,但我不明白为什么其他人即使没有空间也能工作。
答案 0 :(得分:0)
6e可以解释为双重(6e == 6e0 == 6 * pow(10,0) == 6
)格式错误的科学记数法,因此cin >> amount
读取它,>> currency
读取空字符串。
尝试cin >> std::fixed >> amount
(来自<iomanip>
)仅强制“正常”#39}符号。如果这没有帮助(并且它可能不适用于大多数编译器) - 您将必须读取行(std::getline()
)并手动解析(拆分为第一个非数字/ dit或从末尾读取等)