tags:

views:

66

answers:

1

Hi, I'm not very familiar with locale-specific conversions so I may be using the wrong terminology here. This is what I want to have happen.

I want to write a function

std::string changeLocale( const std::string& str, const std::locale& loc )

such that if I call this function as follows:

changeLocale( std::string( "1.01" ), std::locale( "french_france" ) )

the output string will be "1,01"

Thanks for your help!

+5  A: 

Something like this ought to do the trick

#include <iostream>
#include <sstream>
#include <locale>
int main (int argc,char** argv) {
    std::stringstream ss;
    ss.imbue(std::locale("fr_FR.UTF8"));
    double value = 1.01; 
    ss << value; 
    std::cout << ss.str() << std::endl; 
    return 0;
}             

Should give you output of 1,01 (at least it does on g++). You might have to fiddle with the locale specification since it's very specific to platform.

Jeff Foster
+1 for mentioning the platform specific nature of locales.
Nemanja Trifunovic
Thanks Jeff, that does the trick for numeric values on VS2008. I did have to fiddle with the locale specification like you said; the only thing I could get to work was std::locale( "french_france" )Anyway, this solution only works for numeric data. What if my input string was "I weigh 200.5 lbs" and I wanted the output to be "I weigh 200,5 lbs"? Is this possible at all?
Praetorian
Well, 200.5 is a number too right? Or am I misunderstanding your question?
Jeff Foster
What I meant to ask if how do I handle string inputs. For example the following doesn't work: stringstream ss; ss.imbue( locale( "french_france" ) ); string s( "I weigh 200.5 lbs" ); ss << s.c_str(); wcout << ss.str() << endl; The 200.5 in the input remains the same in the output string and I want the output string to be "I weigh 200,5 lbs"
Praetorian
Sorry I'm screwing up the formatting, I have no idea how to format these comment replies, "4 spaces for code" doesn't seem to work.
Praetorian
I was looking to help out on this only to discover that std::locale is busted in a big way on Mac OS X: it only accepts locale names "C" and "POSIX". This seems to be true for at least 10.4 to 10.6. You can still grab the current locale and override various traits; however, you can't load a predefined locale like "fr_FR".
mrkj
@praetorian: If the number is jumbled up in a string, then I think the only option is to take the string apart and get the number, format it, and put it back together again.
Jeff Foster
Crap! I was afraid you'd say that. That seems like it would be hard to make it foolproof; but I'm gonna give it a try. Thanks for your help Jeff.
Praetorian