0

I am trying to make a small program that takes a string and then adds commas to it in three character intervals, like how a currency amount would be formatted. (i.e. 1000 becomes 1,000 and 10000 becomes 10,000).

This is my attempt so far, and it almost works:

 #include <string>
 #include <iostream>
 using namespace std;

 int main() {

  string a = "123456789ab";

  int b = a.length();

  string pos;
  int i;
  for (i = b - 3; i >= 0; i-=3) {
    if (i > 0) {
      pos = "," + a.substr(i,3) + pos;
    }
  }
  cout << pos;
  return 0;
 } 

The output with the sample string is:

,345,678,9ab

It seems it doesn't want to grab the first 1 to 3 characters. What did I do wrong with my code?

Ultimabuster
  • 75
  • 2
  • 8

2 Answers2

0

The first character is at index 0. But you never call substr when i is 0, so you can never get that character.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
0
#include <string>
 #include <iostream>
 using namespace std;

 int main() {

  string a = "123456789ab";

  int b = a.length();

  string pos;
  int i;
  for (i = b - 3; i > 0; i-=3) {
    if (i > 0) {
      pos = "," + a.substr(i,3) + pos;
    }
  }
  cout << a.substr(0,i+3)+pos;
  return 0;
 }

When the index is negative, it means that it can't make any more group of 3. But there may be 1-3 numbers which may be left. We need to explicitly add them

coder hacker
  • 4,819
  • 1
  • 25
  • 50
  • Thanks for your help man, this worked perfectly! Just to understand what you changed a little better, what you added basically takes the first 3 characters of the string and displays them normally right? – Ultimabuster May 10 '14 at 13:14