Author: Embarcadero USA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
Technical Information Database TI2183C.txt Output Numbers with Thousands Separator Category :General Platform :All Product :C/C++ All Description: How do I output comma-formatted numbers such as 1,000,000 with C++ IOStreams? As common as this would seem, C++ IOStreams have no support for this. The function shown in the code sample below serves two purposes: it converts the long to a string and inserts commas every three digits. Adding the commas during the conversion is much easier than converting the long to a string using sprintf() and then modifying the string. For new programmers, this code is an excellent example use of the modulus operator to reverse a string. The reversing algorithm is almost identical to the generic reverse() function in the Standard Template Library. #include const char *commaStr(unsigned long number) { const int size = 15; // max number of digits static char str[size]; // string to return char *ptr1, *ptr2; // place holders char tempStr[size]; // workplace int counter = 0; // three's counter ptr1 = tempStr; do { // grab rightmost digit and add value of character zero *ptr1++ = (char)(number % 10) + '0'; // strip off rightmost digit number /= 10; // if moved over three digits insert comma into string if (number && !(++counter % 3)) *ptr1++ = ','; // continue until number equal zero } while(number); // this loop reverses characters in a string for( --ptr1, ptr2 = str; ptr1 >= tempStr; --ptr1) *ptr2++ = *ptr1; // add the zero string terminator *ptr2 = '0'; return str; } // simple main to test function int main() { cout <<'s "Toolbox". If you're new to programming, it will be worth your time to run the code in the debugger and watch how it works. Use Debug|Evaluate|Modify to see how the modulus works. Then inspect the pointer in the reverse code to understand how it accomplishes its task. CAVEATS ======= N/A BIBLIOGRAPHY ============ N/A Reference: 7/2/98 10:40:36 AM |
Get easy-to-understand information on the modern and professional ways to convert integer to String C++ from this recent blog post.
Article originally contributed by
Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.
Start Free Trial Upgrade Today
Free Delphi Community Edition Free C++Builder Community Edition
Design. Code. Compile. Deploy.
Start Free Trial Upgrade Today
Free Delphi Community Edition Free C++Builder Community Edition