Converting integer to string in C without sprintf

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

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

5条回答
  •  别那么骄傲
    2020-12-17 04:25

    Unfortunately none of the answers above can really work out in a clean way in a situation where you need to concoct a string of alphanumeric characters.There are really weird cases I've seen, especially in interviews and at work.

    The only bad part of the code is that you need to know the bounds of the integer so you can allocate "string" properly.

    In spite of C being hailed predictable, it can have weird behaviour in a large system if you get lost in the coding.

    The solution below returns a string of the integer representation with a null terminating character. This does not rely on any outer functions and works on negative integers as well!!

    #include 
    #include 
    
    
    void IntegertoString(char * string, int number) {
    
       if(number == 0) { string[0] = '0'; return; };
       int divide = 0;
       int modResult;
       int  length = 0;
       int isNegative = 0;
       int  copyOfNumber;
       int offset = 0;
       copyOfNumber = number;
       if( number < 0 ) {
         isNegative = 1;
         number = 0 - number;
         length++;
       }
       while(copyOfNumber != 0) 
       { 
         length++;
         copyOfNumber /= 10;
       }
    
       for(divide = 0; divide < length; divide++) {
         modResult = number % 10;
         number    = number / 10;
         string[length - (divide + 1)] = modResult + '0';
       }
       if(isNegative) { 
       string[0] = '-';
       }
       string[length] = '\0';
    }
    
    int main(void) {
    
    
      char string[10];
      int number = -131230;
      IntegertoString(string, number);
      printf("%s\n", string);
    
      return 0;
    }
    

提交回复
热议问题