Insert and remove commas from integers in C ++

There are a lot of noobs here, so it's best to assume that I don't know anything in the answers.

I am writing a small application and it works well, but readability is a nightmare with my numbers.

Essentially, all I want to do is add commas to the numbers displayed on the screen to make it easier to read. Is there a quick and easy way to do this?

I use stringstream to capture my numbers (I'm not sure why this is even offered at the moment, it was just advised in the tutorial I worked with), for example (cutting out inappropriate bits):

#include <iostream> #include <string> #include <sstream> using namespace std; int items; string stringcheck; ... cout << "Enter how many items you have: "; getline (cin, stringcheck); stringstream(stringcheck) >> items; ... cout << "\nYou have " << items << " items.\n"; 

When this number is typed as something big, among everything else, it becomes quite a headache for reading.

Is there any quick and easy way to print "13 653 456" as opposed to "13653456", as it would be now (provided that, of course, it was introduced)?

Note. If that matters, I am making it a console application in Microsoft Visual C ++ 2008 Express Edition.

+6
c ++
source share
1 answer

Try the numpunct facet and overload do_thousands_sep . There is an example . I also hacked something that just solves your problem:

 #include <locale> #include <iostream> class my_numpunct: public std::numpunct<char> { std::string do_grouping() const { return "\3"; } }; int main() { std::locale nl(std::locale(), new my_numpunct); std::cout.imbue(nl); std::cout << 1000000 << "\n"; // does not use thousands' separators std::cout.imbue(std::locale()); std::cout << 1000000 << "\n"; // uses thousands' separators } 
+16
source share

All Articles