Add leading zero's to string, without (s)printf

后端 未结 7 1787
孤独总比滥情好
孤独总比滥情好 2020-12-08 19:49

I want to add a variable of leading zero\'s to a string. I couldn\'t find anything on Google, without someone mentioning (s)printf, but I want to do this without (s)printf.<

相关标签:
7条回答
  • 2020-12-08 20:07

    You could do something like:

    std::cout << std::setw(5) << std::setfill('0') << 1;
    

    This should print 00001.

    Note, however, that the fill-character is "sticky", so when you're done using zero-filling, you'll have to use std::cout << std::setfill(' '); to get the usual behavior again.

    0 讨论(0)
  • 2020-12-08 20:07
    memcpy(target,'0',sizeof(target));
    target[sizeof(target)-1] = 0;
    

    Then stick whatever string you want zero prefixed at the end of the buffer.

    If it is an integer number, remember log_base10(number)+1 (aka ln(number)/ln(10)+1) gives you the length of the number.

    0 讨论(0)
  • 2020-12-08 20:08
    // assuming that `original_string` is of type `std:string`:
    
    std::string dest = std::string( number_of_zeros, '0').append( original_string);
    
    0 讨论(0)
  • 2020-12-08 20:11

    The C++ way of doing it is with setw, ios_base::width and setfill

    #include <iostream>
    #include <iomanip>
    
    using namespace std;
    
    int main()
    {
        const int a = 12;
        const int b = 6;
    
        cout << setw(width) << row * col;
        cout << endl;
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-08 20:13

    I can give this one-line solution if you want a field of n_zero zeros:

      std::string new_string = std::string(n_zero - old_string.length(), '0') + old_string;
    

    For example: old_string = "45"; n_zero = 4; new_string = "0045";

    0 讨论(0)
  • 2020-12-08 20:18

    This works well for me. You don't need to switch setfill back to ' ', as this a temporary stream.

    std::string to_zero_lead(const int value, const unsigned precision)
    {
         std::ostringstream oss;
         oss << std::setw(precision) << std::setfill('0') << value;
         return oss.str();
    }
    
    0 讨论(0)
提交回复
热议问题