Exercise 3-6 (itoap - Integer to string, padded)
Chapter_3 Exercise_3-5 | trim Chapter_4 |
Exercise 3-6 K&R, p. 64
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.
itoap.c download
#include <stdio.h> // for printf(), scanf()
#define SIZE 100 // array size (max no of digits)
#define WIDTH 8 // could also be 16, 32, or 64
// reverse s[], knowing its length:
void reverse(char s[], int len);
// int to string of chars, minimum field width:
int itoap (int n, char s[], unsigned width);
int main()
{
char digits[SIZE];
int n;
printf ("Give an integer: ");
scanf ("%d", &n);
itoap(n, digits, WIDTH);
printf ("%s\n", digits); // with an eventual sign
return 0;
}
// reverse s[], knowing its length:
void reverse(char s[], int len)
{
int i = 0, j = len-1;
char temp;
while (i < j)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
}
// get the digits of n into s[] (convert n to a string of characters),
// with a minimum field width (padded to the left if necessary),
// return length of s[] (digits, eventual sign):
int itoap (int n, char s[], unsigned width)
{
int i = 0, sign = 1, diff;
if (n < 0)
{
sign = -1;
}
do
{ // get the digits in reverse order:
s[i++] = (n % 10)*sign + '0'; // get next (last read) digit
// if n < 0, (n /= 10) <= 0, (n % 10) < 0
} while (n /= 10); // while ((n /= 10) != 0); // delete last digit
if (sign < 0) {s[i++] = '-';} // first char after reverse
diff = width-i;
while (diff > 0) // while (diff)
{
s[i++] = ' ';
diff--;
}
s[i] = '\0'; // end the string
reverse(s, i);
return i;
}
/*
gcc itoap.c -o itoap
./itoap
Give an integer: 0
0
./itoap
Give an integer: -1
-1
./itoap
Give an integer: 123
123
./itoap
Give an integer: -125
-125
./itoap
Give an integer: 1234567
1234567
./itoap
Give an integer: 12345678
12345678
./itoap
Give an integer: 123456789
123456789
./itoap
Give an integer: -123456
-123456
./itoap
Give an integer: -1234567
-1234567
./itoap
Give an integer: -12345678
-12345678
*/
Chapter_3 Exercise_3-5 | BACK_TO_TOP | trim Chapter_4 |
Comments
Post a Comment