Get number into a string C without stdio

前端 未结 5 1762
忘掉有多难
忘掉有多难 2021-01-21 10:41

I want to know how to get number to string without standard C or C++ functions, for example:

char str[20];
int num = 1234;
// How to convert that number to strin         


        
5条回答
  •  爱一瞬间的悲伤
    2021-01-21 11:33

    A simplistic way to do this is to leave a lot of leading zeros. I like it because it uses only basic code, and doesn't require any dynamic memory allocation. It should consequently also be very fast:

    char * convertToString(int num, str) {
        int val;
    
        val = num / 1000000000; str[0] = '0' + val; num -= val * 1000000000;
        val = num / 100000000;  str[1] = '0' + val; num -= val * 100000000;
        val = num / 10000000;   str[2] = '0' + val; num -= val * 10000000;
        val = num / 1000000;    str[3] = '0' + val; num -= val * 1000000;
        val = num / 100000;     str[4] = '0' + val; num -= val * 100000;
        val = num / 10000;      str[5] = '0' + val; num -= val * 10000;
        val = num / 1000;       str[6] = '0' + val; num -= val * 1000;
        val = num / 100;        str[7] = '0' + val; num -= val * 100;
        val = num / 10;         str[8] = '0' + val; num -= val * 10;
        val = num;              str[9] = '0' + val;
                                str[10] = '\0';
    
        return str;
    }
    

    Of course, there are tons of tweaks you could do to this - modifying the way the destination array gets created is possible, as is adding a boolean that says to trim leading 0s. And we could make this much more efficient using a loop. Here's in improved method:

    void convertToStringFancier(int num, char * returnArrayAtLeast11Bytes, bool trimLeadingZeros) {
        int divisor = 1000000000;
        char str[11];
        int i;
        int val;
    
        for (i = 0; i < 10; ++i, divisor /= 10) {
            val = num / divisor;
            str[i] = '0' + val;
            num -= val * divisor;
        }
        str[i] = '\0';
    
        // Note that everything below here is just to get rid of the leading zeros and copy the array, which is longer than the actual number conversion.
        char * ptr = str;
        if (trimLeadingZeros) {
            while (*ptr == '0') { ++ptr; }
            if (*ptr == '\0') { // handle special case when the input was 0
                *(--ptr) = '0';
        }
        for (i = 0; i < 10 && *ptr != '\0'; ++i) {
        while (*ptr != '\0') {
            returnArrayAtLeast11Bytes[i] = *ptr;
        }
        returnArrayAtLeast11Bytes[i] = '\0';
    }
    

提交回复
热议问题