diff options
| author | Sadeep Madurange <smadurange@users.noreply.github.com> | 2021-12-04 13:31:01 +0800 |
|---|---|---|
| committer | Sadeep Madurange <smadurange@users.noreply.github.com> | 2021-12-04 13:31:01 +0800 |
| commit | ca34f80cacd236c8089e05d9f1fcc7958da3e500 (patch) | |
| tree | 0d75acf146362ab0e1d68abdb2ea4ee6737960c0 | |
| parent | e9798c972782500eaf1a6bc4d5632aa3594642b9 (diff) | |
| download | k&r-exercises-ca34f80cacd236c8089e05d9f1fcc7958da3e500.tar.gz | |
3.6
| -rw-r--r-- | 3/6.c | 66 |
1 files changed, 66 insertions, 0 deletions
@@ -0,0 +1,66 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define MAXLEN 1000 + +/* converts n to s with width w */ +void itoa(int n, char s[], int w); + +int main(int argc, char *argv[]) { + int i, c, n, w; + char s[MAXLEN]; + + printf("Number to convert to string: "); + for (i = 0; i < MAXLEN - 1 && (c = getchar()) != '\n' && c != EOF; i++) + s[i] = c; + s[i] = 0; + n = atoi(s); + + printf("Width: "); + for (i = 0; i < MAXLEN - 1 && (c = getchar()) != '\n' && c != EOF; i++) + s[i] = c; + s[i] = 0; + w = atoi(s); + + itoa(n, s, w); + printf("%d as string of width %d: %s\n", n, w, s); + + return 0; +} + +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; + + i = 0; + + if (n >= 0) { + do { + s[i++] = n % 10 + '0'; + } while ((n /= 10) > 0); + } else { + do { + s[i++] = -(n % 10) + '0'; + } while ((n /= 10) <= -1); + } + + if (n < 0) + s[i++] = '-'; + + while (i < MAXLEN - 1 && i < w) + s[i++] = ' '; + + s[i] = 0; + + reverse(s); +}
\ No newline at end of file |
