题目:
修改itoa函数,使得该函数可以接收三个参数。其中,第三个参数为最小字符宽度。为了保证转换后所得的结果至少具有第三个参数指定的最小宽度,在必要时在所得结果的左边填充一定的空格。
书中的itoa函数为:
#include <stdio.h>
#include <string.h>
void itoa(int n, char s[])
{
int i, sign;
if((sign = n) < 0)
n = -n;
i = 0;
do
{
s[i++] = n % 10 + '0';
}
while((n /= 10) > 0);
if(sign < 0)
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;
}
}
自我解答:
只需在转换结束之后,增加一个当前字符数组大小和最小宽度的判断,如果小于最小字符宽度,就补齐空格。
void reverse(char s[]);
void itoa(int n, char s[], int minWid)
{
int i, sign;
if((sign = n) < 0)
n = -n;
i = 0;
do
{
s[i++] = n % 10 + '0';
}
while((n /= 10) > 0);
if(sign < 0)
s[i++] = '-';
while(minWid > i)
s[i++] = ' ';
s[i] = '\0';
reverse(s);
}
参考答案:
#define abs(x) ((x) < 0 ? -(x) : (x))
/* itoa: convert n to characters in s, w characters wide */
void itoa(int n, char s[], int w)
{
int i, sign;
void reverse(char s[]);
sign = n; /* record sign */
i = 0;
do /* generate digits in reverse order */
{
s[i++] = abs(n % 10) + '0'; /* get next digit */
}
while((n /= 10) != 0); /* delete it */
if(sign < 0)
s[i++] = '-';
while(i < w)
s[i++] = ' ';
s[i] = '\0';
reverse(s);
}
上面这个函数与练习3-4中的itoa导函数很相似。我们对其做了必要的修改:
while(i < w)
s[i++] = ' '
这个while循环的作用是在必要时给字符串s补足空格。