练习1-18 编写一个程序,删除每个输入行末尾的空格及制表符,并删除完全是空格的行。
#include <stdio.h>
#define MAXLINE 1000
int getline(char s[], int lim);
int remove_tail(char s[]);
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
int len, len1;
char line[MAXLINE];
while ((len = getline(line, MAXLINE)) > 0) {
len1 = remove_tail(line);
if (len1 > 0) {
printf("[%d]%s", len1, line);
}
}
return 0;
}
int getline(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++;
}
s[i] = '\0';
return i;
}
int remove_tail(char s[])
{
int i = 0;
while(s[i] != '\0') {
i++;
}
i--;
if (s[i] == '\n') {
i--;
}
while (i >= 0 && (s[i] == '\t' || s[i] == ' ')) {
i--;
}
if (i >= 0) {
s[++i] = '\n';
s[++i] = '\0';
}
return i;
}
运行结果:
标签:练习题,int,18,char,++,len1,lim,程序设计,line From: https://blog.csdn.net/VincentKCSDN/article/details/141759236