Adding commas to numbers

Hello everyone,

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.I was able to get it up to the 100 thousands and have it output a comma properly. But my problem is, my code is set to 100 thousand and , if i get it up to the millions or even billions, I would have to add extra commas. But if a person puts in a value lower than a million or billion, I would have extra commas because I am using cout to output them. Thus, I was wondering if it was possible to really have this program go from 1000 up to just about anything and have a universal rules for commas or would there have to be a limit, like say 1,000 to 999,999? -Thank you. Also, my code so far so you can see what I mean:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>


using namespace std;

int main()

{
	cout << "Please enter a number greater than or equal to 1000 without a comma.\n";
	string number;
	cin >> number;
	
	int n = number.length();
	string first_half = number.substr(0, n-3 );
	int n2 = first_half.length(); 
	string second_half = number.substr(n2 ,3);
	cout << first_half << "," << second_half << endl;
}
closed account (D80DSL3A)
The string class has an insert function.
Start at the end and insert a "," every 3rd space back to the beginning.

I just wrote such a program to be sure it would work. It does.
If this is not homework and you would like to see this code, then ask and I'll post it.

Give it a try first though.
Oh ok, so it is possible then to go up to a very large number. Thanks alot and I will get back to trying that.
Topic archived. No new replies allowed.