Created
November 12, 2009 06:17
-
-
Save shaobin0604/232652 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 <limits.h> | |
#define abs(x) ((x) > 0) ? (x) : -(x) | |
void itoa(int n, char s[], int width); | |
void reverse(char s[]); | |
int main(void) { | |
char buffer[20]; | |
itoa(INT_MIN, buffer, 20); | |
printf("Buffer:%s\n", buffer); | |
return 0; | |
} | |
void itoa(int n, char s[], int width) { | |
int i, sign; | |
sign = n; | |
i = 0; | |
do { | |
s[i++] = abs(n % 10) + '0'; | |
} while ((n /= 10) != 0); | |
if (sign < 0) | |
s[i++] = '-'; | |
while (i < width ) /* Only addition to original function */ | |
s[i++] = ' '; | |
s[i] = '\0'; | |
reverse(s); | |
} | |
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; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment