Getting money from C++

By gracefu on

One way of getting money from C++ is a job, but today I learnt of an easier way, std::get_money.

Taken from the cppreference page:

#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>

int main()
{
    std::istringstream in("$1,234.56 2.22 USD  3.33");
    long double v1, v2;
    std::string v3;
    in.imbue(std::locale("en_US.UTF-8"));
    in >> std::get_money(v1) >> std::get_money(v2) >> std::get_money(v3, true);
    if (in) {
        std::cout << std::quoted(in.str()) << " parsed as: "
                  << v1 << ", " << v2 << ", " << v3 << '\n';
    } else {
        std::cout << "Parse failed";
    }
}

// "$1,234.56 2.22 USD  3.33" parsed as: 123456, 222, 333

Yeah. I love locales in my language!

Of course, if you decide that you have too much money, you can also std::put_money back.

std::cout.imbue(std::locale("ja_JP.UTF-8"));
std::cout << "ja_JP: " << std::showbase << std::put_money(mon)
          << " or " << std::put_money(mon, true) << '\n';

// ja_JP: ¥123 or JPY  123

By the way, if you get too much money, it's possible that the authorities might come after you if you're not careful. Don't forget to std::launder it!

long double money;
std::cin.imbue(std::locale("en_US.UTF-8"));
std::cin >> std::get_money(money);

long double *safe_money_location;
if (money > 500000) {
  // Not actually a useful use of std::launder, btw
  safe_money_location = std::launder(&money);
} else {
  safe_money_location = &money;
}

std::cout.imbue(std::locale("en_US.UTF-8"));
std::cout << "I have money: " << std::showbase
          << std::put_money(*safe_money_location) << '\n';

I mean, sure. C++ has locales, and locales have money. Still, C++ has some pretty funny things in the language.

Back to home page