Recently do a problem, using recursive method to convert integer n into a string, do a half-day to find a library function directly can realize this function, really day dog ....
Waiter, on the code ...
#include <stdio.h> #include <stdlib.h> #include <string.h>// This turnover function is to reverse the string, Because the string is inverted when n is converted to a string in the CONVERT function// is the use of an intermediate variable to exchange the string array s to the end of the Char *turnover (char *s) { int i,j; // Temporary variables char c; // temporary variables j=strlen (s) -1; // gets the string with the length of the character because the string is then ' s ', so minus 1 for (i=0;i<=j/2;i++) // Cycle once Exchange { c=s[j]; s[j--]=s[i]; s[i]=c; } return s;} converts integer n to string Char *convert (int n,char *s) { char c[]={' 0 ', ' + '}; // A temporary variable used to store the character c[0]=n%10+ ' 0 ' of the last peel from N; // converts the bits of n into characters, stored in c[0] strcat (s,c); // connection S and c n/=10; // n are peeled off a if (n!=0) // Recursive start ... convert (n,s); else return turnover (s);} Int main () { int&NBSP;N;&NBSP;CHAR&NBSP;S[100],*STR;&NBSP;SCANF ("%d", &n), str=convert (n,s); printf ("%s\n", str);}
In fact, converting n into a string also has a more convenient library function int sprintf (char *s, "...", various parameters);
The first parameter of this function is the first address of the string, the second argument is the format string, and the third is the format control. The return value is the length of the character string. Use the following:
#include <stdio.h> #include <string.h>int main () {char buffer[80]; int n,i; scanf ("%d", &n); i=sprintf ( Buffer, "%d", n); printf ("%s\n", buffer); printf ("%d", I);}
The output is:
650) this.width=650; "title=" capture. PNG "src=" http://s3.51cto.com/wyfs02/M01/6B/E0/wKiom1U4qRiwEl0JAABdEMgWenc356.jpg "alt=" Wkiom1u4qriwel0jaabdemgwenc356.jpg "/>
method of converting an integer n to a string