gpt4 book ai didi

c++ - 以char 'e'为输入进行比较

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:49:20 27 4
gpt4 key购买 nike

好的,所以我正在做一个书中的练习,将不同类型的货币转换为美元。出于某种原因,当我输入“e”作为 char 变量的输入并将其与 if 语句中的“e”进行比较时,比较不起作用,但是如果我将其替换为另一个字母,它将正常工作。这是怎么回事?继承人的代码:

int main()
{
const double yen_per_dollar = .013;
const double pound_per_dollar = 1.55;
const double euro_per_dollar = 1.29;

double amount = 1;
char unit = ' ';

std::cout << "Please enter a amount followed by a unit (p, y, or e): ";
std::cin >> amount >> unit;

if (unit == 'y')
std::cout << amount << " yen is $" << amount * yen_per_dollar << " dollars.\n";
if (unit == 'p')
if (amount == 1)
std::cout << amount << " pound is $" << amount * pound_per_dollar << " dollars.\n";
else
std::cout << amount << " pounds is $" << amount * pound_per_dollar << " dollars.\n";
if (unit == 'e')
if (amount == 1)
std::cout << amount << " euro is $" << amount * euro_per_dollar << " dollars.\n";
else
std::cout << amount << " euros is $" << amount * euro_per_dollar << " dollars.\n";
else
std::cout << "Sorry, that input isn't in the correct format." << std::endl;
std::cin >> amount; // Keeps window open
}

最佳答案

有很多评论,但没有解决方案。事实上,我也想不出一个好的解决方案。我能想到的最好的办法是安装一个自定义的 num_get 方面(仅此一项几乎可以肯定地将代码排除在适合作为家庭作业解决方案上交):这是有点高级的东西,我不想不到很多人会想到这一点。

除此之外,我认为您想要数据驱动货币,即您不想为每种货币设置一个代码分支,而是想要设置某种描述所有货币的容器(顺便说一句,复数欧元是欧元)。生成的程序看起来像这样:

#include <iostream>
#include <locale>
#include <string>
#include <tuple>
#include <map>
#include <ctype.h>

struct currency_get:
std::num_get<char>
{
iter_type do_get(iter_type it, iter_type end, std::ios_base&, std::ios_base::iostate& err, double& v) const
{
std::string input;
for (; it != end && (*it == '.' || *it == '-' || *it == '+'
|| isdigit(static_cast<unsigned char>(*it))); ++it)
{
input.push_back(*it);
}
errno = 0;
if (input.empty())
{
err |= std::ios_base::failbit;
}
else
{
v = strtod(input.c_str(), 0);
}

return it;
}
};

int main()
{
typedef std::tuple<double, std::string, std::string> desc;
std::map<char, desc> currencies;
currencies['y'] = desc(0.013, "yen", "yen");
currencies['p'] = desc(1.55, "pound", "pounds");
currencies['e'] = desc(1.29, "euro", "euro");

double amount(0);
char currency(' ');
std::locale loc(std::locale(), new currency_get);
std::cin.imbue(loc);

if (std::cin >> amount >> currency)
{
std::map<char, desc>::const_iterator it(currencies.find(currency));
if (it != currencies.end())
{
desc const& d(it->second);
std::cout << amount << " " << (amount == 1? std::get<1>(d): std::get<2>(d)) << " is "
<< (std::get<0>(d) * amount) << " dollar"
<< (std::get<0>(d) * amount == 1? "": "s") << "\n";
}
}
else
{
std::cout << "input failed\n";
}
}

关于c++ - 以char 'e'为输入进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8707675/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com