Comma Formatting for numbers in C++

前端 未结 5 871
北海茫月
北海茫月 2020-12-17 05:30

I\'m needing help in adding commas to the number the user enters, some guidance or help would be appreciated. So far I have it where i store the first three digits and the l

5条回答
  •  借酒劲吻你
    2020-12-17 05:52

    EDIT: I have two solutions. first without playing with numbers (recommended) and second (division). first solution is:

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    struct my_facet : public std::numpunct{
            explicit my_facet(size_t refs = 0) : std::numpunct(refs) {}
            virtual char do_thousands_sep() const { return ','; }
            virtual std::string do_grouping() const { return "\003"; }
    };
    
    /*
     * 
     */
    int main(int argc, char** argv) {
    
        cout<<"before. number 5000000: "<<5000000<

    before. number 5000000: 5000000
    after. number 5000000: 5,000,000

    and again as before. number 5000000: 5000000

    RUN SUCCESSFUL (total time: 54ms)

    and second (not recommended) is :

    double f = 23.43;
    std::string f_str = std::to_string(f);
    

    or this

    int a = 1;
    stringstream ss;
    ss << a;
    string str = ss.str();
    

    Then you can use string::substr() string::find() string::find_first_of() and similar methods to modify and format your string.
    a similar topic


    If you really want (have to) divide: (I think my version is cleaner & more efficient than the others)

    unsigned long long userInput;
        std::stringstream ss,s0;
        std::string nr;
            std::cout << "Enter a long long number: " << std::endl;
            std::cin >> userInput;
            int input=userInput;
            int digits;
    
            while(input>999){
                input=input/1000;
                digits=userInput-input*1000;
                int mdigits=digits;
                while(mdigits<100){s0<<"0";mdigits*=10;}
                std::string s=ss.str();
                ss.str("");
                ss<<","<

    Enter a long long number: 12345678 Your Number: 12;345;12,345,678

提交回复
热议问题