# Commas, I'm Stumped

Show 80 post(s) from this thread on one page
Page 2 of 2 First 12
• 02-13-2005
StarOrbs
See I've been working on this problem for almost 2 weeks and we are only allowed to use things that we learned in class, so we can't use loops or even if else statements. This is a pain in the ass.
• 02-13-2005
Salem
Well you could use the ?: operator, but that's really just another if/else, so would it count.
Also, you're not likely to have come across it.

Code:

```cout << (x/1000)%1000; cout << ","; cout << x%1000;```
Something along these lines, but without if statements, you'll end up with output like
000,000,123
000,134,765
• 02-13-2005
Dave Evans
Quote:

Originally Posted by StarOrbs
I've been messing around with a bunch of combinations of % and / and adding new variables multipling and divivding the first and second part of the calculations. I tried to logically write down a piece of paper what would do it. When I enter 1200 I get 1,200 but when I got up to one more zero I get this, I enter 12,000 and get 12,0 and when I enter 120,000 I get 120,0 ... Looks like there are 2 zeros missing.. Very Confusing. lol.. Well thanks for your help everyone hopefully I'll be able to get it tommorow. :)

If you can't use conditional statements to decide when to print trailing zeros, I have to ask if you have had anything in class about formatting output to cout? (Specifically ostream member functions width() and fill().)

If so, look at what this does, and maybe you can see how they could solve your problem:

Code:

```#include <iostream> using std::cout; using std::endl; int main() {   int i;   int x = 1234;   for (i = 1; i < 10; i++) {     cout.width(i);     cout << x << endl;   }   cout << endl;   cout.fill('0');   for (i = 1; i < 10; i++) {     cout.width(i);     cout << x << endl;   }   cout.width(3); cout.fill('0');   cout << endl;   x = 12;   cout << x << endl;   return 0; }```
Regards,

Dave
• 02-13-2005
Hunter2
Gee, sucks that you can't use 'if'. Well, something like this might work (though I haven't tested it):

**EDIT** Oops, didn't notice you can't use loops. Well, I'm out of ideas then :(

Code:

```int lengthOfNewString = strlen(strNumber) + strlen(strNumber) / 3;  //Increase size for commas char* newString = new char[lengthOfNewString + 1];  //Leave room for '\0' newString[lengthOfNewString] = '\0'; int pos = strlen(strNumber) - 1; int nsPos = lengthOfNewString - 1; int iterations = strlen(strNumber) / 3; for(int i = 0; i < iterations; ++i) {   newString[nsPos] = strNumber[pos];   newString[nsPos - 1] = strNumber[pos - 1];   newString[nsPos - 2] = strNumber[pos - 2];   newString[nsPos - 3] = ',';   nsPos -= 4;   pos -= 3; } int remainingDigits = strLen(strNumber) % 3; for(int i = 0; i < remainingDigits; ++i) {   newString[nsPos] = strNumber[pos];   --nsPos;   --pos; }```
Show 80 post(s) from this thread on one page
Page 2 of 2 First 12