khalfella

ansi_c_pg059_ch03_ex06.c

Dec 27th, 2014
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. /*
  2. * Exercise 3-6.
  3. * Write a version of itoa that accepts three arguments instead of two. The
  4. * third argument is a minimum field width; the converted number must be padded
  5. * with blanks on the left if necessary to make it wide enough.
  6. */
  7.  
  8. #include <stdio.h>
  9. #include <string.h>
  10. /* reverse: reverse string s in place */
  11. void
  12. reverse(char s[])
  13. {
  14. int c, i, j;
  15. for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
  16. c = s[i];
  17. s[i] = s[j];
  18. s[j] = c;
  19. }
  20. }
  21.  
  22.  
  23. void
  24. itoa(int n, char s[], int w)
  25. {
  26. int i, sign;
  27. unsigned int un = n;
  28. if ((sign = n) < 0) /* record sign */
  29. un = -n; /* make n positive */
  30. i = 0;
  31. do { /* generate digits in reverse order */
  32. s[i++] = un % 10 + '0'; /* getnextdigit */
  33. } while ((un /= 10) > 0);
  34. if (sign < 0)
  35. s[i++] = '-';
  36.  
  37. while (w > i)
  38. s[i++] = ' ';
  39.  
  40. s[i] = '\0';
  41. reverse(s);
  42. }
  43.  
  44. int
  45. main(int argc, char **argv)
  46. {
  47. char s[100];
  48. itoa(2147483648, s, 30);
  49. printf("\"%s\"\n", s);
  50. return (0);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment