diff options
| author | Sadeep Madurange <smadurange@users.noreply.github.com> | 2021-11-21 13:06:29 +0800 |
|---|---|---|
| committer | Sadeep Madurange <smadurange@users.noreply.github.com> | 2021-11-21 13:06:29 +0800 |
| commit | f72ba11006b4b4496709d38fea0ac4854d5ba30f (patch) | |
| tree | 9f8df7d1374c936bb8e1a5d02f960388b936cd92 | |
| parent | ea74e68369f44bf5766704db626c23b001f5fdc3 (diff) | |
| download | k&r-exercises-f72ba11006b4b4496709d38fea0ac4854d5ba30f.tar.gz | |
1.21
| -rw-r--r-- | 1/20.c | 7 | ||||
| -rw-r--r-- | 1/21.c | 59 |
2 files changed, 63 insertions, 3 deletions
@@ -8,14 +8,15 @@ void detab(char to[], char from[], int n); /* detabs input by replacing tabs with specified number of blanks */ int main(int argc, char *argv[]) { + int tabw; char s[MAXLEN], dtab[MAXLEN]; - int tabw = atoi(argv[1]); - printf("Enter text to detab and press ctrl+d\n"); + tabw = atoi(argv[1]); + printf("Enter text to detab and press ctrl+d\n"); + getstr(s); detab(dtab, s, tabw); - printf("\nTab width: %d\n", tabw); printf("%s\n", dtab); @@ -0,0 +1,59 @@ +#include <stdio.h> +#include <stdlib.h> + +#define MAXLEN 1000 + +void getstr(char s[]); +void entab(char to[], char from[], int n); + +/* replaces specified number of blanks with a tabstop */ +int main(int argc, char *argv[]) { + int tabw; + char s[MAXLEN], tabbed[MAXLEN]; + + tabw = atoi(argv[1]); + + printf("Enter text to entab and press ctrl+d\n"); + + getstr(s); + entab(tabbed, s, tabw); + printf("\nTab width: %d\n", tabw); + printf("%s\n", tabbed); + + return 0; +} + +void getstr(char s[]) { + int i, c; + + for (i = 0; i < MAXLEN - 1 && (c = getchar()) != EOF; i++) + s[i] = c; + s[i] = '\0'; +} + +void entab(char to[], char from[], int n) { + int i, j, k, op; + char c; + + for (i = 0, j = 0; j < MAXLEN - 1 && (c = from[j]) != '\0'; i++) { + if (c == ' ') { + op = j + n < MAXLEN - 1; + for (k = j + 1; op && k < j + n - 1; k++) { + if (from[k] != ' ') { + op = 0; + } + } + + if (op) { + to[i] = '\t'; + j += n; + continue; + } + } + + to[i] = c; + j++; + } + + to[i] = '\0'; +}
\ No newline at end of file |
