Converting integer to string in C without sprintf

后端 未结 5 2054
一向
一向 2020-12-17 03:56

It is possible to convert integer to string in C without sprintf?

5条回答
  •  独厮守ぢ
    2020-12-17 04:15

    There's a nonstandard function:

    char *string = itoa(numberToConvert, 10); // assuming you want a base-10 representation
    

    Edit: it seems you want some algorithm to do this. Here's how in base-10:

    #include 
    
    #define STRINGIFY(x) #x
    #define INTMIN_STR STRINGIFY(INT_MIN)
    
    int main() {
        int anInteger = -13765; // or whatever
    
        if (anInteger == INT_MIN) { // handle corner case
            puts(INTMIN_STR);
            return 0;
        }
    
        int flag = 0;
        char str[128] = { 0 }; // large enough for an int even on 64-bit
        int i = 126;
        if (anInteger < 0) {
            flag = 1;
            anInteger = -anInteger;
        }
    
        while (anInteger != 0) { 
            str[i--] = (anInteger % 10) + '0';
            anInteger /= 10;
        }
    
        if (flag) str[i--] = '-';
    
        printf("The number was: %s\n", str + i + 1);
    
        return 0;
    }
    

提交回复
热议问题