How to convert an int to string in C?

后端 未结 10 2141
南方客
南方客 2020-11-22 02:51

How do you convert an int (integer) to a string? I\'m trying to make a function that converts the data of a struct into a string to save it in a fi

10条回答
  •  一个人的身影
    2020-11-22 03:17

    /*Function return size of string and convert signed  *
     *integer to ascii value and store them in array of  *
     *character with NULL at the end of the array        */
    
    int itoa(int value,char *ptr)
         {
            int count=0,temp;
            if(ptr==NULL)
                return 0;   
            if(value==0)
            {   
                *ptr='0';
                return 1;
            }
    
            if(value<0)
            {
                value*=(-1);    
                *ptr++='-';
                count++;
            }
            for(temp=value;temp>0;temp/=10,ptr++);
            *ptr='\0';
            for(temp=value;temp>0;temp/=10)
            {
                *--ptr=temp%10+'0';
                count++;
            }
            return count;
         }
    

提交回复
热议问题