Got a question about printing Integers with thousands/millions separator.
I got a Textfile where i got Country, City,Total Population.
I have to read in the
Use a locale which supports the desired separators to read the file (that way you can read the values as integers), and the same locale to write the data.
Note that you may not have such a locale available, or if you
do, you may not know its name (and using a named locale might
change other things, that you don't want changed); on my
machine, imbue
ing with ""
behaves differently according to
the compiler (or maybe the shell I'm invoking it from)—you
should never use the locale ""
if you have strict formatting
requirements. (The use of locale ""
is for the case when you
want the format to depend on the users environment
specifications.)
In this case, it's probably better to provide the local explicitly:
class MyNumPunct : public std::numpunct<char>
{
protected:
virtual char do_thousands_sep() const { return ','; }
virtual std::string do_grouping() const { return "\03"; }
};
int
main()
{
std::cout.imbue( std::locale( std::locale::classic(), new MyNumPunct ) );
std::cout << 123456789 << std::endl;
return 0;
}
Of course, you'll want to use this locale for the input as well.
(This code will give you the "C"
locale, with only the
grouping changed.)
imbue() the output stream with a locale that has the desired separator. For example:
#include <iostream>
#include <locale>
int main()
{
// imbue the output stream with a locale.
int i = 45749785;
std::cout << i << "\n";
std::cout.imbue(std::locale(""));
std::cout << i << "\n";
}
Output on my machine (and online demo):
45749785 45,749,785
As commented, and answered, by James Kanze imbue the input stream also to read the separated int
values without manually modifying the input.
See Stroustrop's Appendix D: Locales for a detailed overview of locales.