int to string without itoa

2010-11-01 6:41 pm
How to type casting for int to String for C program?

I want to change int to string without using build-in function itoa()!
更新1:

Can you show me the code

更新2:

我要唔用內部 function 將int to String 123 --> "123"

回答 (3)

2010-11-02 5:55 am
✔ 最佳答案

Writing your own version of itoa() on the contrary is quite simple. Just for reference, here is an example of how itoa() works:

#include <stdio.h>
//#include <string.h>

// Function declarations
// typedef __w64 unsigned int size_t
size_t strlen(const char *);
char *strrev(char *);
char *itoa(int, char *, int);

int main() {
int num = 123;
char buf[5];

itoa(num, buf, 10);

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

return 0;
}

size_t strlen(const char *string) {
const char *s;

s = string;
while (*s)
s++;
return s - string;
}

char *strrev(char *str) {
char *p1, *p2;

if (!str || !*str)
return str;

for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) {
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}

return str;
}

char *itoa(int n, char *s, int b) {
static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
int i=0, sign;

if ((sign = n) < 0)
n = -n;

do {
s[i++] = digits[n % b];
} while ((n /= b) > 0);

if (sign < 0)
s[i++] = '-';
s[i] = '\0';

return strrev(s);
}
2010-11-03 2:02 pm
Then use sprintf.
2010-11-01 7:35 pm
This program is in The C Programming Book by K&R


收錄日期: 2021-05-01 23:53:47
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20101101000051KK00306

檢視 Wayback Machine 備份