magnus
magnus

Reputation: 4261

Why is this C++ money_put<char> program not working?

I am experimenting with C++ locales, and cannot work out why the output is 0.05 instead of 4.98.

#include <iostream>
#include <vector>
#include <string>
#include <locale>
using namespace std;

int main(int argc, const char** argv) {


    vector<string> locales;
    locales.push_back("de_DE");
    locales.push_back("en_AU");
    locales.push_back("en_GB");
    locales.push_back("zh_CN");

    long double amount = 4.98;
    for (size_t i = 0, s = locales.size(); i < s; ++i) {
        if (locales[i] != "C") {
            cout.imbue(locale(locales[i].c_str()));
            cout << i << " (" << locales[i] << "): ";

            const moneypunct<char>& mp = use_facet<moneypunct<char> >(cout.getloc());
            const money_put<char>& mv = use_facet<money_put<char> >(cout.getloc());

            cout << mp.curr_symbol();
            ostreambuf_iterator<char> out(cout);
            mv.put(out, false, cout, cout.fill(), amount);
            cout << endl;
        }
    }

    return 0;
}

The output of the program is below:

0 (de_DE): Eu0,05
1 (en_AU): $0.05
2 (en_GB): £0.05
3 (zh_CN): ¥0.05

What am I doing wrong?

Upvotes: 0

Views: 168

Answers (2)

user657267
user657267

Reputation: 21030

[locale.money.put.virtuals]

The argument units is transformed into a sequence of wide characters as if by

ct.widen(buf1, buf1 + sprintf(buf1, "%.0Lf", units), buf2)

You can find exhaustive info on the cppreference page.

Upvotes: 1

magnus
magnus

Reputation: 4261

The (simplified) answer is that the money_put<char>.put() function refers to a long double parameter called units. This is the units in cents, not dollars.

Upvotes: 3

Related Questions