-2

Example from CS106B course book about strings. The sense of program is to add comma after every three digit from the end. In case of input 15000 output must be 15,000. As you see, I have ignored digits shorter then 4.

/*
 * File: AddCommas.cpp
 * -----------------
 *
 */

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

/*Function prototypes*/
string addCommas(string digits);

/*Main program*/
int main(){
    while(true){
        string digits;
        cout << "Enter a number: ";
        getline(cin, digits);
        if (digits == "") break;
        cout << addCommas(digits) << endl;
    }
    return 0;
}

/*Function: addCommas
 *Usage: string addCommas(string digits)
 *---------------------------------------
 *Adds commas to long digits
 */
string addCommas(string digits){
    string result;
    if (digits.length() > 3){
        int t = 0;

        for(int i = digits.length() - 1; i >= 0; i --){
            result = digits[i] + result;
            t++;
            if(t%3 == 0){
                result = ',' + result;

            }
        }
        if(result[0] == ','){
            result.erase(0, 1);
        }
    } else {
        result = digits;
    }
    return result;
}
Tsiskreli
  • 103
  • 1
  • 11
  • 2
    You may want to opt for a more general solution using the locale features of the standard library, [See this for an example](http://en.cppreference.com/w/cpp/locale/num_put). It would be considerably more robust. – WhozCraig Feb 13 '14 at 21:00
  • homework? Someone close this? – Alex Feb 13 '14 at 21:10

2 Answers2

1

This may be too advanced for a beginner, but maybe this would be ok as it relies on only 2 std::string methods. Be prepared to explain how it works!

//   out                    in: string of only digits
std::string digiCommaL(std::string s) 
{
   // insert comma's from right (at implied decimal point) to left
   int32_t sSize = static_cast<int32_t>(s.size()); // sSize MUST be int

   if (sSize > 3)
      for (int indx = (sSize - 3);  indx > 0;  indx -= 3)
         s.insert(static_cast<size_t>(indx), 1, ',')

   return(s);
}
2785528
  • 5,438
  • 2
  • 18
  • 20
0

My solution of this example. I had to add some extra code to avoid such things: ,200,000 it happened when string length%3==0

Tsiskreli
  • 103
  • 1
  • 11