Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 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.
- */
- #include <stdio.h>
- #include <string.h>
- /* reverse: 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;
- }
- }
- void
- itoa(int n, char s[], int w)
- {
- int i, sign;
- unsigned int un = n;
- if ((sign = n) < 0) /* record sign */
- un = -n; /* make n positive */
- i = 0;
- do { /* generate digits in reverse order */
- s[i++] = un % 10 + '0'; /* getnextdigit */
- } while ((un /= 10) > 0);
- if (sign < 0)
- s[i++] = '-';
- while (w > i)
- s[i++] = ' ';
- s[i] = '\0';
- reverse(s);
- }
- int
- main(int argc, char **argv)
- {
- char s[100];
- itoa(2147483648, s, 30);
- printf("\"%s\"\n", s);
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment