我是一名初学者,正在通过Bjarne Stroustrup的PPP书籍工作。我正在写一个简单的程序来转换货币,而且我在处理这个角色时会得到一个奇怪的角色' e。当我在money_value和currency_type输出之间输入空格时,该程序按预期工作。所有其他"货币"按预期工作。有什么想法吗?
#include "../../std_lib_facilities.h"
int main()
{
cout << "Currency conversions\n\n";
constexpr double pound = 1.32;
constexpr double euro = 1.17;
constexpr double yen = 0.0089;
double currency_value;
char currency_type;
cout << "Please enter a currency value followed by currency type ((e)uro, (y)en, (p)ound:\n\n";
cin >> currency_value >> currency_type;
cout << "\n\n";
if (currency_type == 'e')
{
cout << currency_value << " euro = " << euro*currency_value << " dollars. \n\n";
}
else if (currency_type == 'y')
{
cout << currency_value << " yen = " << yen*currency_value << " dollars. \n\n";
}
else if (currency_type == 'p')
{
cout << currency_value << " pound = " << pound*currency_value << " dollars. \n\n";
}
else
{
cout << "Sorry, I don't know a currency called " << currency_type << ". \n\n";
}
}
答案 0 :(得分:0)
它将e
视为科学数字的计算机编程表示,即6.022e+23
。其他字母并不意味着什么,所以它将它们放入char中。您应该以std :: string的形式读取此货币,复制最后一个char,修剪字符串的最后一个字符,然后将字符串std :: stod转换为您的货币值。
#include "../../std_lib_facilities.h"
int main()
{
cout << "Currency conversions\n\n";
constexpr double pound = 1.32;
constexpr double euro = 1.17;
constexpr double yen = 0.0089;
string curtemp = "";
double currency_value;
char currency_type;
cout << "Please enter a currency value followed by currency type ((e)uro, (y)en, (p)ound:\n\n";
cin >> curtemp;
cout << "\n\n";
currency_type = curtemp[curtemp.length()-1];
currency_value = std::stod(curtemp.substr(0,curtemp.length()-1));
if (currency_type == 'e')
{
cout << currency_value << " euro = " << euro*currency_value << " dollars. \n\n";
}
else if (currency_type == 'y')
{
cout << currency_value << " yen = " << yen*currency_value << " dollars. \n\n";
}
else if (currency_type == 'p')
{
cout << currency_value << " pound = " << pound*currency_value << " dollars. \n\n";
}
else
{
cout << "Sorry, I don't know a currency called " << currency_type << ". \n\n";
}
}