Boost logo

Boost :

Subject: Re: [boost] [lexical_cast] locale dependent result? (was: [lexical_cast] locale dependent result?)
From: Artyom (artyomtnk_at_[hidden])
Date: 2011-03-02 07:54:46


> Is the result of lexical_cast<std::string> locale-dependent? One of my
> contributors has submitted a fix for a problem he says is caused by
> lexical_cast adding commas to a port number, e.g.: 65535 becomes "65,535".
>
> I'm unable to reproduce this but it may be something specific to his
> locale.

Yes it is,

It is easily reproducible:

    // under Linux
    std::locale::global(std::locale("en_US.UTF-8"));
    // under Windows + Visual Studio
    std::locale::global(std::locale("English_USA"));

    std::string ss=boost::lexical_cast<std::string>(65535);

>
>
> If this is the case, what would be the correct way to get a canonical,
> locale-independent string from an integer?
>
> Thanks.
>
> Alex
>

If you want to do casting without locale context (which is desirable)

    std::ostringstream ss;
    ss.imbue(std::locale::classic()); // C locale
    ss << 65535;
    return ss.str();

Unfortunately this problem is very common and causes
many bugs, especially in C with setlocale and printf.

Artyom

      


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk