【问题标题】:Confusion over std::get_money and std::put_money in C++C++ 中对 std::get_money 和 std::put_money 的混淆
【发布时间】:2019-09-10 19:06:48
【问题描述】:

我对 <iomanip> 头文件中定义的 C++ 函数 std::get_money 感到困惑。根据编程概念,get_money 有什么用?

我有以下代码使用std::get_money

#include <iostream>     // std::cin, std::cout
#include <iomanip>      // std::get_money

int main ()
{
  long double price;
  std::cout << "Please, enter the price: ";
  std::cin >> std::get_money(price);

  if (std::cin.fail()) std::cout << "Error reading price\n";
  else std::cout << "The price entered is: " << price << '\n';

  return 0;
}

当我输入 100.25 时,它返回 100。输出和货币格式之间的关系是什么?我阅读了this 参考,但无法理解这种关系。 std::put_moneystd::get_timestd::put_time 也存在同样的混淆。

有哪些实际使用的例子?

【问题讨论】:

标签: c++ iomanip


【解决方案1】:

这是我不知道存在的标准库的一部分!根据cppreference,您必须设置语言环境来定义时间和金钱的格式。这里我使用的是 en_US 语言环境。

#include <iomanip>
#include <iostream>

int main() {
  long double price;
  std::cin.imbue(std::locale("en_US.UTF-8"));
  std::cout << "Please enter the price: ";
  std::cin >> std::get_money(price);
  if (std::cin.fail()) {
    std::cout << "Error reading price\n";
  } else {
    std::cout << "The price entered is: " << price << '\n';
  }
}

不过,这对我来说似乎有点挑剔。该号码必须包含一个.,后面至少有两位数字。 $ 是可选的。

【讨论】:

  • 在抛出 'std::runtime_error' 实例后调用终止 what(): locale::facet::_S_create_c_locale name not valid get that error after include locale
  • @Encipher 听起来您的系统不支持该语言环境。
  • @Encipher 而不是试图让它工作,你可以读入double,乘以100,然后四舍五入到一个整数。
  • 永远不要用花车/双打来赚钱!
  • @graham.reeds 我同意你的观点,但没有看到这个答案中使用的方法存在问题。我看不到将double 舍入为整数(乘以 100 之后)并用整数进行所有算术运算(就像我在评论中提到的那样)的问题。我也没有看到将整数值存储在double 中的问题(std::get_money 返回美分)。 double 具有 54 位整数精度,足以无损存储 32 位 int。将100.25 美元存储在double 中绝对是一个禁忌,但我们不会在这里这样做。
猜你喜欢
  • 2021-01-26
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 2016-07-19
  • 2023-03-18
  • 2015-08-28
  • 2015-02-14
相关资源
最近更新 更多