您的位置:首页 > 编程语言 > Go语言

[Algorithms, C] long2char: 自己用C写来玩玩的整形转化为字符串函数 (递归和迭代两种实现): void long2char(long from, char *to, int n);

2011-06-19 23:06 489 查看
void long2char(long from, char *to, int n); // 递归和迭代两种实现

/* long2char.c
* Author: dooit.lee@gmail.com
* Date: Sun Jun 19, 2011
*/
#include <stdio.h>
#include <stdlib.h>
/*
* from: int, to: char*, `n' means n digits of `from' with to[n + 2]
*/
void long2char(long from, char *to, int n)
{
int digit;
if (from < 0) {
*to = '-';
to++;
from = -1 * from;
}
#if 0	// Recursion
digit = from % 10;
if ((from /= 10) != 0) {
long2char(from, to, n - 1);
}
to[n - 1] = '0' + (digit - 0);
#else	// Iteration
do {
digit = from % 10;
to[--n] = '0' + (digit - 0);
} while ((from /= 10) != 0);
#endif
}
int main(int argc, char *argv[])
{
long from;
int n, i;
char *to, *endptr;
if (argc != 2 || !atoi(argv[1])) {
bad:		fprintf(stderr, "Usage: %s <integer-number>/n", argv[0]);
exit(1);
} else {
from = strtol(argv[1], &endptr, 10);
if (argv[1] == endptr) goto bad;
n = 1;
i = from;
while ((i /= 10) != 0) ++n;
// include a '-' and '/0' charachter
to = calloc(n + 2, sizeof(char));
if (to != NULL) {
long2char(from, to, n);
printf("%s/n", to);
free(to);
} else {
fprintf(stderr, "%s: Cannot allocate memory/n",
argv[0]);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐