Skip to content

Commit

Permalink
Exerc 3_04.
Browse files Browse the repository at this point in the history
  • Loading branch information
rsm-lisper committed May 15, 2024
1 parent fb7e983 commit 564a5d7
Show file tree
Hide file tree
Showing 4 changed files with 94 additions and 0 deletions.
25 changes: 25 additions & 0 deletions chapter_3.control_flow/3_04.itoa/Makefile
Original file line number Diff line number Diff line change
@@ -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
63 changes: 63 additions & 0 deletions chapter_3.control_flow/3_04.itoa/main.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# include <stdio.h>
# include <limits.h>
# include <string.h>

# 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;
}
}
Empty file.
6 changes: 6 additions & 0 deletions chapter_3.control_flow/3_04.itoa/tests/t0.tout
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
0: 0
578678: 578678
-98173: -98173
2147483647: 2147483647
-2147483647: -2147483647
-2147483648: -2147483648

0 comments on commit 564a5d7

Please sign in to comment.