diff options
| author | Zhineng Li <im@zhineng.li> | 2026-05-29 11:52:36 +0800 |
|---|---|---|
| committer | Zhineng Li <im@zhineng.li> | 2026-05-29 11:52:36 +0800 |
| commit | c80f4af866508cf2812ba030bf7abfb70d126b6e (patch) | |
| tree | 8be8ee6bf45e002495ddf0c62939b71e76ff1063 /ch01 | |
| parent | 3cbdab1805a49e3529c3b90932c11208578dd2cc (diff) | |
| download | c-knr-exercises-c80f4af866508cf2812ba030bf7abfb70d126b6e.tar.gz c-knr-exercises-c80f4af866508cf2812ba030bf7abfb70d126b6e.zip | |
Diffstat (limited to 'ch01')
| -rw-r--r-- | ch01/ex21-entab.c | 89 |
1 files changed, 89 insertions, 0 deletions
diff --git a/ch01/ex21-entab.c b/ch01/ex21-entab.c new file mode 100644 index 0000000..1282c61 --- /dev/null +++ b/ch01/ex21-entab.c @@ -0,0 +1,89 @@ +#include <stdio.h> + +#define TABSTOP 8 /* number of columns between tab stops */ +#define DEBUG 0 /* display tabs and spaces explicitly */ + +#define SYM_SP '.' /* visible space for debugging */ +#define SYM_TAB '~' /* visible tab for debugging */ + +void puttab(void); +void putspace(int len); + + +/* replace blanks by proper tabs */ +int main() +{ + int c; /* current character */ + int offset; /* position inside current tab stop */ + int nspace; /* number of spaces */ + + if (DEBUG) { + printf("# debug mode is on\n"); + printf("# displaying spaces and tabs explicitly\n"); + printf("# space -> %c\n", SYM_SP); + printf("# tab -> %c\n", SYM_TAB); + } + + offset = nspace = 0; + while ((c = getchar()) != EOF) { + ++offset; + + if (c == ' ') + ++nspace; + else if (c == '\t') { + puttab(); + offset = nspace = 0; + } else if (nspace) { + putspace(nspace); + nspace = 0; + } + + if (offset == TABSTOP) { + if (nspace) + puttab(); + offset = nspace = 0; + } + + if (c == '\n') { + if (nspace) + putspace(nspace); + offset = nspace = 0; + } + + if (c != ' ' && c != '\t') + putchar(c); + } + + if (nspace) + putspace(nspace); + + return 0; +} + +/* print a tab */ +void puttab(void) +{ + int c; + + if (DEBUG) + c = SYM_TAB; + else + c = '\t'; + + putchar(c); +} + +/* print len spaces */ +void putspace(int len) +{ + int i; + int c; + + if (DEBUG) + c = SYM_SP; + else + c = ' '; + + for (i = 0; i < len; ++i) + putchar(c); +} |
