diff options
| author | Zhineng Li <[email protected]> | 2026-02-04 12:00:07 +0800 |
|---|---|---|
| committer | Zhineng Li <[email protected]> | 2026-02-04 12:00:07 +0800 |
| commit | bdc39e9353244eb5ee665273b86bc3c5a120c030 (patch) | |
| tree | 3e5535ae2f2d7aca7f3ebe335f5b04765590f7e6 /ch01 | |
| parent | 6c133eab750473e3b0e1a342fafe55ba6f1a9c93 (diff) | |
| download | c-knr-exercises-bdc39e9353244eb5ee665273b86bc3c5a120c030.tar.gz c-knr-exercises-bdc39e9353244eb5ee665273b86bc3c5a120c030.zip | |
ch01-18: remove trailing blanks and tabs from each line of input
Diffstat (limited to 'ch01')
| -rw-r--r-- | ch01/ex18-rtrim.c | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/ch01/ex18-rtrim.c b/ch01/ex18-rtrim.c new file mode 100644 index 0000000..b01d2ef --- /dev/null +++ b/ch01/ex18-rtrim.c @@ -0,0 +1,54 @@ +#include <stdio.h> +#define MAXLINE 1000 /* maximum input line size */ + +int getln(char line[], int maxline); +int rtrim(char line[], int len); + +/* remove trailing blanks and tabs from each line of input */ +int main() +{ + int len; /* current line length */ + char line[MAXLINE]; /* current input line */ + + while ((len = getln(line, MAXLINE)) > 0) + if ((len = rtrim(line, len)) > 0) + printf("%s", line); + return 0; +} + +/* getln: read a line into s, return length */ +int getln(char s[], int lim) +{ + int c, i; + + for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) + s[i] = c; + if (c == '\n') { + s[i] = c; + ++i; + } + return i; +} + +/* rtrim: remove trailing blanks and tabs */ +int rtrim(char s[], int len) +{ + int nl = 0; + + if (s[len-1] == '\n') { + nl = 1; + --len; + } + + while (len > 0 && (s[len-1] == ' ' || s[len-1] == '\t')) + --len; + + if (nl == 1) { + s[len] = '\n'; + ++len; + } + + s[len] = '\0'; + + return len; +} |
