-1

i'm suppose 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 the exact same. So 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;
}
Christian
  • 35
  • 7

1 Answers1

0

It seems, you 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';
    }
    
Dietmar Kühl
  • 145,940
  • 13
  • 211
  • 371