Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - C language reads an integer from the keyboard and converts it into a string for output. For example, if you enter 123, it will be converted into the string "123".
C language reads an integer from the keyboard and converts it into a string for output. For example, if you enter 123, it will be converted into the string "123".
The library function sprintf can complete the function you want. If you want to realize it yourself, simply write it down, and the function may not be perfect:

# include & ltstdio.h & gt

# include & ltassert.h & gt

# include & ltstring.h & gt

//Now you can add a conversion base radix in the parameter part, and you can convert the remainder for different decimals (only consider the negative sign when radix== 10 at this time).

void my_itoa(char *buffer,const int num)

{

int temp = num,I = 0;

Assertion (buffer! = NULL);

if(temp & lt; 0)

{

buffer[I]= '-'; //Negative situation

i++;

temp =-temp; //become a positive number, which is convenient for the remainder operation.

}

for(; Temperature; i++)

{

buffer[I]= temp % 10+' 0 '; //Loop the last bit of num and put it in the buffer until 0.

temp/= 10;

}

if(num & lt; 0)

//Non-standard library function, which can realize the flipping of the flipping string by itself (omitted here)

_ strrev(& amp; buffer[ 1]); //If it is negative, only the part after the negative sign will be flipped.

other

_strrev (buffer); //Flip All to flip the flipped string back again.

}

int main(int argc,char *argv[])

{

int a =- 123;

char str[32]= " \ 0 ";

my_itoa(str,a);

printf("%s\n ",str);

sprintf(str," %d ",a);

printf("%s\n ",str);

Returns 0;

}