我应该编写一个简单的程序来去除尾随空格和制表符的行。它应该用 C 中最基本的工具编写(没有指针和库)。
/* Write a program to remove trailing blanks and tabs from each
line of input, and to delete entirely blank lines. */
#include <stdio.h>
#define MAXLINE 1000
int gettline(char s[], int lim);
void inspect_line(char s[], int limit, int start, int end);
main()
{
int len, i, start, end;
start = 0;
end = MAXLINE;
char line[MAXLINE];
while ((len = gettline(line, MAXLINE)) > 0){
inspect_line(line, MAXLINE, start, end);
for(i=start; i<end-1;++i)
printf("%c",line[i]);
}
printf("\n");
return 0;
}
/* gettline: read a line into s, return length */
int gettline(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;
}
/* inspect_line: determines the indices to the start and the end of the sentence */
void inspect_line(char s[], int limit, int start, int end)
{
while((s[start]!=' ') && (start<limit-1))
++start;
while(!(s[end]>=33 && s[end]<=126))
--end;
}
当我运行它时,我得到了一个奇怪的结果:
我不确定问题出在哪里,我已经尝试调试了几个小时但没有结果。
最佳答案
事情是这样的:当你写的时候
inspect_line(line, MAXLINE, start, end);
for(i=start; i<end-1;++i)
printf("%c",line[i]);
您假设在 inspect_line
函数中设置为 start
和 end
的值将被传输到 main
;这个假设是不正确的。在 C 中,参数是按值传递的。这就是为什么 start
和 end
保持调用前的状态。
您可以通过将指向 start
和 end
的指针传递到 inspect_line
函数中来解决此问题。当然,您也需要更改函数以接受和使用指针:
void inspect_line(char s[], int *start, int *end)
{
while(isspace(s[*start]) && (*start < *end))
++(*start);
while(isspace(s[*end]) && (*start < *end))
--(*end);
}
调用看起来像这样:
// Note that passing MAXLINE is no longer necessary
inspect_line(line, &start, &end);
for(i=start ; i <= end-1 ; ++i) // both start and end are inclusive
printf("%c",line[i]);
您还需要在循环的每次迭代之间重新初始化 start
和 end
,将 start
设置为零并将 end
为 len
的当前值。
关于c - 从文本行的两侧删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25751392/