: : : Write a program that reads a number greater than or equal to 1000 from the user and prints it out with a comma seperating the thousands. Here is a sample dialog; the user input in color:
: : :
: : : Please enter an integer >= 1000 : 23456
: : :
: : : 23,456
: : :
: : : Can anyone figure this out?
: : Well, you already have the number in string form (because you read it from the console). Now all you have to do is count off characters from the right and insert a comma after every three digits. You can insert the commas while copying the digits to a new string, or you can insert them in place. This will give you practice on looping and string handling at the character level. It's not going to be easy, but you can always post here for help.
: : Cheers,
: : Eric
: I dont know how to do the looping thing...im getting very different answer freom people and im getting even more confused... can u do one example?
Don't get too stressed, it's not as easy as it might first appear. The easiest way to do it is to output each character one at a time, inserting commas as needed. Since you're using std::string, to access individual characters you can use operator, or using string::iterator. As in:
for (int = 0; i < s.length(); ++i)
for (string::iterator it = s.begin(); it != s.end(); ++it)
or you could use pointers, but basic_string::iterator really is just char* anyway, and the iterator is cleaner.
Anyway, the real trick is knowing when to insert a comma. We need to know when we're at the end of a "three digit group". Well we know we need to insert commas after the digits 3,6,9,12,etc. Multiples of three, right? How do we find out in code if a number is a multiple of three? Just divide by 3; if there's no remainder, it's an even multiple. Of course, anytime we need the remainder of an integer division, we know we're going to be using the mod operator (%).
Let's say we have the number:
Let's number the digits, right to left:
the number : 84903928
digits index: 87654321
Digit 1: 1%3==1
Digit 2: 2%3==2
Digit 3: 3%3==0 .. end of a group of 3 digits, need a comma here
Digit 4: 4%3==1
Digit 5: 5%3==2
Digit 6: 6%3==0 .. end of a group of 3 digits, need a comma here
Digit 7: 7%3==1
Digit 8: 8%3==2
So now we have mathematical way of determining if we're at a digit that needs a comma.
Small problem. In our 'legend' above we number the digits [N..1] (with the 'first' digit on the right). However, in C++ you index digits in a string [0..N-1] (with the 'first' digit on the left). So you'll have to reconcile that in your program. The easiest way is to loop from N to 1, as in "for (int i = length; i >= 1; --i)", or something like that. If (i % 3 == 0), we know we need to insert a comma.
Hopeful that helps and doesn't just confuse the crap out of you. ;)