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)
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
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
unsignedint 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
unsignedint CommaOffset = ln%3; // Get the comma offset
for(unsignedint 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!