diff --git a/chapter_3.control_flow/3_04.itoa/Makefile b/chapter_3.control_flow/3_04.itoa/Makefile new file mode 100644 index 0000000..1f10e34 --- /dev/null +++ b/chapter_3.control_flow/3_04.itoa/Makefile @@ -0,0 +1,25 @@ +BINARY=itoa + +CFILES=$(wildcard *.c) +TESTDIR=./tests/ +TESTS=$(wildcard $(TESTDIR)*.tin) +TEST_RESULTS=$(patsubst %.tin,%.res,$(TESTS)) + +CC=gcc +CFLAGS=-Wall -Wextra -Werror -ggdb -std=c89 + + +all: $(BINARY) + +$(BINARY): $(CFILES) + $(CC) $(CFLAGS) -o $@ $^ + +check: $(TEST_RESULTS) + +%.res: %.tin + @./$(BINARY) <$? >$@ult + @diff --color=always --text $@ult $(patsubst %.tin,%.tout,$?) + +clean: + rm -f $(BINARY) + rm -f $(TESTDIR)*.result diff --git a/chapter_3.control_flow/3_04.itoa/main.c b/chapter_3.control_flow/3_04.itoa/main.c new file mode 100644 index 0000000..a8df3f6 --- /dev/null +++ b/chapter_3.control_flow/3_04.itoa/main.c @@ -0,0 +1,63 @@ +# include +# include +# include + +# define MAXLEN 128 + +void itoa (int n, char s[]); +void reverse (char s[]); +void test_itoa (int n); + + +int main() +{ + test_itoa(0); + test_itoa(578678); + test_itoa(-98173); + test_itoa(INT_MAX); + test_itoa(INT_MIN+1); + test_itoa(INT_MIN); + return 0; +} + + +void test_itoa (int n) +{ + char s[MAXLEN]; + + itoa(n, s); + printf("%d: %s\n", n, s); +} + + +void itoa (int n, char s[]) +{ + int i, sign; + unsigned int nn; + + if ((sign = n) < 0) { /* record sign */ + nn = -n; /* make n positive */ + } else { + nn = n; + } + i = 0; + do { /* generate digits in reverse order */ + s[i++] = nn % 10 + '0'; /* get next digit */ + } while ((nn /= 10) > 0); /* delete it */ + if (sign < 0) + s[i++] = '-'; + s[i] = '\0'; + reverse(s); /* reverse digits order */ +} + + +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; + } +} diff --git a/chapter_3.control_flow/3_04.itoa/tests/t0.tin b/chapter_3.control_flow/3_04.itoa/tests/t0.tin new file mode 100644 index 0000000..e69de29 diff --git a/chapter_3.control_flow/3_04.itoa/tests/t0.tout b/chapter_3.control_flow/3_04.itoa/tests/t0.tout new file mode 100644 index 0000000..ab58b33 --- /dev/null +++ b/chapter_3.control_flow/3_04.itoa/tests/t0.tout @@ -0,0 +1,6 @@ +0: 0 +578678: 578678 +-98173: -98173 +2147483647: 2147483647 +-2147483647: -2147483647 +-2147483648: -2147483648