Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting and removing commas from integers in c++

Tags:

c++

Very much a noob here, so it's best to assume I know nothing in any answers.

I've been writing a little app, and it's working well, but readability is a nightmare with my numbers.

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

I've been using stringstream to grab my numbers (I'm not sure why this is even suggested at this point, it was simply advised in the tutorial I worked through), such as(cropping out the irrelevent 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 that number is typed as something large, amongst everything else it becomes quite a headache to read.

Is there any quick and easy way to make it print "13,653,456" as opposed to "13653456" like it would right now (assuming that's what was input of course)?

Note: If it matters, I'm making this as a console application in Microsoft Visual C++ 2008 Express Edition.

like image 751
Dmatig Avatar asked Apr 26 '09 17:04

Dmatig


2 Answers

Try the numpunct facet and overload the do_thousands_sep function. There is an example. I also hacked up 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
} 
like image 64
dirkgently Avatar answered Sep 22 '22 10:09

dirkgently


you can create a locale as explained by dirkgently, although you can also use the appropriate locale, for example

`#include <locale>
int main() {
    std::cout.imbue(std::locale("en_US.utf8"));
    std::cout << 123456789 << '\n';
}`
like image 30
Alon Kwart Avatar answered Sep 22 '22 10:09

Alon Kwart