Convert a number to a string with specified length in C++

后端 未结 8 1360
情深已故
情深已故 2020-12-04 23:36

I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then tho

8条回答
  •  臣服心动
    2020-12-05 00:05

    This method doesn't use streams nor sprintf. Other than having locking problems, streams incur a performance overhead and is really an overkill. For streams the overhead comes from the need to construct the steam and stream buffer. For sprintf, the overhead comes from needing to interpret the format string. This works even when n is negative or when the string representation of n is longer than len. This is the FASTEST solution.

    inline string some_function(int n, int len)
    {
        string result(len--, '0');
        for (int val=(n<0)?-n:n; len>=0&&val!=0; --len,val/=10)
           result[len]='0'+val%10;
        if (len>=0&&n<0) result[0]='-';
        return result;
    }
    

提交回复
热议问题