Can you put an integer from a variable, for example:
int i=17;
char array[]= i;
and now i want to have
array[3]= {1,7,\0}
I know it doesn't work this way but i dont know how to do it without some special functions, which i dont want to use. Thank you for your help.
this is what i came up with:
char array[];
int counter = 172; //the number i want to put into string
int i= 0;
int p=0;
float c = counter;
int k=0, g=0, h=0;
while(counter !=0){
counter = counter /10;
c= c/10;
p++;
}
while(p !=0){
c=c*10;
k=c;
h= k-g;
g=k*10;
array[i] = h;
i++;
p--;
}
array[i]= '\0';
Use sprintf(buffer, "%d", i);
Make sure that buffer
is long enough to contain any possible number-string and the terminating \\0
byte.
sprintf
accepts everything that printf
does, but sends its output to a string buffer instead of STDOUT.
If you really don't want to use sprintf, then here is a sample code snippet for you.
#define BASE 10
#define MAXLEN 10
int val = 153;
char valstr[MAXLEN];
//Reverse the int
int valcpy = val;
int valrev = 0;
while(valcpy) {
valrev *= BASE;
valrev += valcpy % BASE;
valcpy /= BASE;
}
//Convert to string
int i = 0;
while(valrev) {
valstr[i] = valrev % BASE + '0';
valrev /= BASE;
i++;
}
valstr[i] = '\0';
printf("%d = %s", val, valstr); //prints 153 = 153
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.