Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion over std::get_money and std::put_money in C++

Tags:

c++

iomanip

I am confused with the C++ function std::get_money defined in the <iomanip> header file. What is the use of get_money as per programming concept?

I have the following code using 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;
}

When I typed in an input of 100.25 it returned 100. What is the relation between the output and monetary format? I read this reference but cannot understand the relation. The same confusion is present with std::put_money, std::get_time, and std::put_time.

What are some examples of its actual use?

like image 865
Encipher Avatar asked Apr 21 '19 04:04

Encipher


1 Answers

This is a part of the standard library that I didn't know existed! According to cppreference, you have to set the locale to define how time and money should be formatted. Here I'm using the en_US locale.

#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';
  }
}

Still, this seems a bit finicky to me. The number must include a . with at least two digits after it. The $ is optional.

like image 172
Indiana Kernick Avatar answered Nov 20 '22 06:11

Indiana Kernick