-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy path3-6.c
72 lines (54 loc) · 1.29 KB
/
3-6.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* Exercise 3-6. Write a version of itoa that accepts three arguments instead
* of two. The third argument is a minimum field width; the converted number
* must be padded with blanks on the left if necessary to make it wide enough.
*
* By Faisal Saadatmand
*/
#include <stdio.h>
#include <string.h>
#include <limits.h>
#define MAXLEN 1000
/* functions */
void reverse(char []);
void itoa(unsigned, char [], int);
/* reverse function: reverse string s in place */
void reverse(char s[])
{
int c, i, j;
for (i = 0, j = strlen(s) - 1; i < j; i++, j --) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
/* itoa: convert n to characters in s */
void itoa(unsigned n, char s[], int w)
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in revered order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
/* left padding */
while (i < w)
s[i++] = ' ';
s[i] = '\0';
reverse(s);
}
int main(void)
{
int intValue, width;
char str[MAXLEN];
printf("Enter integer to convert to a string: ");
scanf("%i", &intValue);
printf("Enter minimum field width: ");
scanf("%i", &width);
itoa(intValue, str, width);
printf("%s\n", str);
return 0;
}