put a comma in a number (HELP !!)

Hello everyone,

i am beginnerin c++ and I was just attempting a program from the book where it asks to write a program that readers a number greater than or equal to 1000 but outputs it with a comma separating the thousands(1,000).

i dont have any idea how to solve it but all i know is i have to use xx.length() then i use xx.substr(xx,xx)

can anyone help ...

Convert number to a C++ string.
Insert comma in position three from the end.
Then insert comma in position six+1 from the end.
Then insert comma in position nine+2 from the end.
etc
etc
Last edited on
can you explain more how can i insert comma in position three from the end ???
Last edited on
If you read up on the string class, you'll find helpful member functions.

http://www.cplusplus.com/reference/string/string/
First convert the number into a C++ String.
Create a new C++ String, empty.
Add character by character, and if ((Index%3)==Comma Offset) add a comma.
Like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::string NumericString = "1234567890"; // It should output 1,234,567,890
unsigned int Length = strlen(NumericString.c_str()); // Get the length of the string, so we know when we have to stop
std::string FinalString; // Will be our output
unsigned int CommaOffset = ln%3; // Get the comma offset
for(unsigned int i = 0; i < Length; ++i) // Loop each character
{
    // If our Index%3 == CommaOffset and this isn't first character, add a comma
    if(i%3 == CommaOffset && i)
    {
        FinalString += ','; // Add the comma
    }
    FinalString += NumericString.c_at()[i]; // Add the original character
}
// Done! 
Last edited on
Topic archived. No new replies allowed.