38 lines
718 B
C
38 lines
718 B
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
|
||
|
void itoar(char *s, int x);
|
||
|
|
||
|
/* converts first arg to int, puts it to output with itoar */
|
||
|
int main(int argc, char *argv[])
|
||
|
{
|
||
|
if (argc < 2)
|
||
|
return 1;
|
||
|
int x = atoi(argv[1]);
|
||
|
char s[strlen(argv[1])+1];
|
||
|
itoar(s, x);
|
||
|
printf("%s\n", s);
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
char * utoar(char *s, unsigned x);
|
||
|
|
||
|
/* itoa: writes int x to string s in decimal
|
||
|
* recursive implementation */
|
||
|
void itoar(char *s, int x)
|
||
|
{
|
||
|
unsigned y = (x < 0) ? *(s++) = '-', -x : x;
|
||
|
s = utoar(s, y);
|
||
|
*s = '\0';
|
||
|
}
|
||
|
|
||
|
/* utoar: helper for itoa */
|
||
|
char * utoar(char *s, unsigned x)
|
||
|
{
|
||
|
if (x / 10)
|
||
|
s = utoar(s, x / 10);
|
||
|
*s = x % 10 + '0';
|
||
|
return s+1;
|
||
|
}
|