【发布时间】: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++