-1

I'm supposed to allow the user to input as a C string "xxx,xxx,xxx.xx" (x's are digits). So if I input "343,111,222.00" then the output would be exactly the same. So my question is if this is how it's done? I think what I want to do, is if the user puts "123456", then the output automatically inputs "123,456.00". Any advice/tips/critique is appreciated.

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>

int main() {

    using namespace std;
    char myStr[256];    
    char tempStr[256];
    double sum = 0; //Adding sum soon.
    int decreaseDist;

    cout << "Enter Any integers ";
     cin.getline(myStr,256);
    cout << endl;

    int finalCount = 0;

    int i;
    long distToDot = tempStr[256] - 3;
   
    for(i=0; myStr[i] != '\0'; i++) {
            putchar(myStr[i]);
            decreaseDist = distToDot = i;
   
            if(i !=0 && decreaseDist > 0 && decreaseDist % 3== 0) {
                    tempStr[finalCount++] = ',';
            }
           
            tempStr[finalCount++] = myStr[i];
    }
    tempStr[finalCount] = '\0';

    return 0;
}
user438383
  • 5,716
  • 8
  • 28
  • 43
Christian
  • 35
  • 7
  • Have a look at http://stackoverflow.com/questions/7276826/c-format-number-with-commas to see how you can do this sort of thing :) – yamafontes Oct 20 '13 at 20:37

1 Answers1

0

It seems your question has two parts:

  1. How are decimal numbers always displayed with exactly two fractional digits. The answer to this question is to set up the stream to use fixed formatting and a precision of 2:

    std::cout << std::setprecision(2) << std::fixed;
    
  2. The other part of the question seems to ask how to create thousands separators. The answer to this question is to use a std::locale with a suitable std::numpunct<char> facet, e.g.:

    struct numpunct
        : std::numpunct<char> {
        std::string do_grouping() const { return "\3"; }
    };
    int main() {
        std::cout.imbue(std::locale(std::locale(), new numpunct));
        std::cout << double(123456) << '\n';
    }
    
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380