summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSadeep Madurange <smadurange@users.noreply.github.com>2021-11-21 13:06:29 +0800
committerSadeep Madurange <smadurange@users.noreply.github.com>2021-11-21 13:06:29 +0800
commitf72ba11006b4b4496709d38fea0ac4854d5ba30f (patch)
tree9f8df7d1374c936bb8e1a5d02f960388b936cd92
parentea74e68369f44bf5766704db626c23b001f5fdc3 (diff)
downloadk&r-exercises-f72ba11006b4b4496709d38fea0ac4854d5ba30f.tar.gz
1.21
-rw-r--r--1/20.c7
-rw-r--r--1/21.c59
2 files changed, 63 insertions, 3 deletions
diff --git a/1/20.c b/1/20.c
index a4f38cb..7ec32ac 100644
--- a/1/20.c
+++ b/1/20.c
@@ -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);
diff --git a/1/21.c b/1/21.c
new file mode 100644
index 0000000..8648ee2
--- /dev/null
+++ b/1/21.c
@@ -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