c - 从文本行的两侧删除空格

标签 c text tabs space

我应该编写一个简单的程序来去除尾随空格和制表符的行。它应该用 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;
}

当我运行它时,我得到了一个奇怪的结果:

enter image description here

我不确定问题出在哪里,我已经尝试调试了几个小时但没有结果。

最佳答案

事情是这样的:当你写的时候

inspect_line(line, MAXLINE, start, end);
for(i=start; i<end-1;++i)
    printf("%c",line[i]);

您假设在 inspect_line 函数中设置为 startend 的值将被传输到 main;这个假设是不正确的。在 C 中,参数是按值传递的。这就是为什么 startend 保持调用前的状态。

您可以通过将指向 startend 的指针传递到 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]);

您还需要在循环的每次迭代之间重新初始化 startend,将 start 设置为零并将 endlen 的当前值。

关于c - 从文本行的两侧删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25751392/

相关文章:

php - 如何在 PHP 中获得 C 的连续输出

python - 使用 python 读取大型文本文件比使用 Matlab 读取相同文本的相同代码慢得多,知道为什么吗?

visual-studio-2013 - Visual Studio 2013选项卡包装故障

javascript - 当我使用 Angular md-selected 索引频繁切换选项卡时,多个 'md-tab' 同时具有 'md-active' 类

jquery - tabber 在页面加载时闪烁

c - 在 C 中减少内存使用的一些最佳实践是什么?

规范模式 Linux 串口

c - 如何在 C 中使用指针获取多维数组的输入并打印数组?

CSS 文本背景颜色被切断

linux - 如何采用成对的线并连接起来?