Function that adds commas between groups of 3 digits in a string My program contains some very large integers and uses the GMP library. The output contains integers (probably small enough to fit into int). I would like to make the output easy to read by adding commas between every three digits with any left overs on the left side.

Examples:

1234 =&gt; 1,234
12345 =&gt; 12,345
123456 =&gt; 123,456
123 =&gt; 123


The input of the function would be a string representing an integer, because the value of the mpz_class would be converted to a string. I know there's been a lot of discussion of adding commas to int but not string. The mpz_class can't be converted to an int because it may be too big.

Here is what I have and it isn't pretty. 

using namespace std;

/*add commas between groups of 3 digits with remainder on left side*/
string addCommas(string in)
{
    const int length = in.length();
    if(length &lt; 4)
    {
        return in;
    }
    int inserted = 0;
    int i = length % 3;
    if(i == 0)
    {
        i = 3;
    }
    for(; i &lt; length + inserted; i = i + 4)
    {
        in.insert(i, ",");
        inserted++;
    }
    return in;
}


Given its use in the program, it is guaranteed the input will not be a negative number. Though I still wonder if it's good to include a check? The program focuses on quick results. How can this code be more readable?
Avoid using namespace std

The standard namespace isn't designed to be imported wholesale, and name collisions could later appear that silently change the meaning of your program (such as when you add an extra include, or move to a newer C++ standard).

std::string::insert moves content multiple times

We're not very efficient, because the later characters will be shuffled as many times as there are preceding commas inserted.  Worse, we don't even reserve() enough space to add the commas, so there could (theoretically at least) be multiple memory allocations.

Don't reinvent the wheel

It would be simpler and more flexible to use std::numpunct to perform the formatting.