Just a few notes from the view of someone who has implemented this stuff...
news.hku.hk said:
but how to return to the original state??
If you only need an occasional switch between locales, you can just switch
them by calling 'imbue()', eg.:
std::locale english("English");
std::cout.imbue(english);
// ...
std::cout.imbue(std::locale());
The default constructor just uses a copy of the global locale (internally,
locales are a reference counted collection of facets and copying them is
fast). However, the 'imbue()' operation itself is relatively expensive.
In particular, it is reasonable for streams to cache quite a few values
obtained from a locale to improve the overall performance. As a result,
you might consider to use a separate stream writing to the same destination
but with a different locale, eg.:
std:
stream ecout(std::cout.rdbuf());
ecout.imbue(std::locale("English"));
ecout << "english: " << 10000 << "\n";
std::cout << "normal: " << 10000 << "\n";
Since creation of streams themselves is also relatively expensive, you
might want to keep the additional stream around rather than creating it
each time around (which would probably be more expensive than switching
locales).
Also, the names for the named locales are not specified by the standard.
Of course, you can figure out which locales are around when porting your
application to another compiler/library but for portable code you would
probably create an own locale with a specialized 'std::numpunct<char>'
facet. Here is a brief code example (entirely untested, however...):
#include <locale>
class mynumpunct:
public std::numpunct<char> {
std::string do_grouping() const {
char group[] = { 3, 0 };
return group;
}
};
int main() {
std::locale myloc(std::locale(), new mynumpunct);
std::cout.imbue(myloc);
// ...
}
Actually, you can do funny things with the grouping: it does not have to
be the same amount of characters every time! For example, if 'group'
would be initialized like
char group[] = { 1, 2, 3, 0 };
you would get "1,234,56,7" when printing "1234567" (as an integer, that is;
grouping is not applied to strings, of course).
also, from your quotation, if i add one more cout line after cout << 12345
<<'\n';
i.e. cout << 543532 << '\n';
there will be runtime error.......what's up ??
This seems to be an error somewhere in the code you use: there should be
no problem using 'std::cout' even with a modified locale.