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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With