首页 文章

C - 用空格替换制表符,用1个空格替换多个空格,用1换行替换多个换行符

提问于
浏览
1

我被要求编写一个简单的程序,根据众所周知的循环“格式化”文本:

int c;
while ((c = getchar()) != EOF)
   putchar(c);

程序从stdin读取并写入stdout并应使用I / O重定向进行测试 .

  • 输入中的每个选项卡都替换为空格,然后输出中的一个空格替换两个或多个连续的空格 .

  • 输入中的两个或多个连续空行被输出中的一个空行替换 .

注意:换行符是行的最后一个字符,而不是下一行的第一个字符 .

这是我到目前为止,但我输入文本文件中的倍数空格,换行符和标签不会在输出文本文件中被替换:

#include <stdio.h>

int main (void){

int c;
int spacecount = 0;
int newlinecount = 0;

while ((c = getchar()) != EOF){

    if (c == '\n'){
        if (++newlinecount < 3){
            putchar(c);
        }
        continue;
    }

    newlinecount = 0;

    if (c == ' '){
        if (++spacecount < 2){
            putchar(c);
        }
        continue;   
    }

    spacecount = 0;

    if (c == '\t'){
        c = ' ';
    }
    putchar(c);
}

return 0;

}

1 回答

  • 1

    Remove All Blank Lines & Compressing All Tab & Spaces to 1 Space

    你遇到的最大问题是如果遇到 ' ''\n' ,你需要用较小的数字替换多次出现,你需要继续读取(在你的外部 while 循环中),直到找到一个字符为止 . 不是 ' ''\n' . 这简化了记录您的计数 . (并且不需要 spacecountnewlinecount

    由于您正在测试多个字符,当您发现第一个字符与当前搜索字符不匹配时,只需将其放回 stdin 并移至外部while循环的下一次迭代 .

    将所有 tabsspaces 压缩为单个 space 时,需要在单个 if 语句中测试 tabspace .

    把它们放在一起,你可以做到:

    #include <stdio.h>
    
    int main (void) {
    
        int c;
    
        while ((c = getchar ()) != EOF)
        {
            if (c == '\r') continue;
            if (c == '\n') {        /* handle newlines/carriage-returns */
                putchar (c);
                while ((c = getchar ()) == '\n' || c == '\r') {}
                if (c != EOF) ungetc (c, stdin); else break;
                continue;
            }
            if (c == ' ' || c == '\t') {  /* spaces & tabs */
                putchar (' ');
                while ((c = getchar ()) == ' ' || c == '\t') {}
                if (c != EOF) ungetc (c, stdin); else break;
                continue;
            }
            putchar (c);
        }
        return 0;
    }
    

    note: 代码已更新,以处理DOS / windoze \r\n 行结尾以及Linux '\n'

    Example Input

    $ cat dat/gcfmt.txt
    
    N <tab> description
    21      grapes
    18      pickles
    
    
    
    N <spaces> description
    23         apples
    51         banannas
    
    
    
    <spaces>N<tab>  description
            8       cherries
            4       mellons
            6       strawberries
    
    
    that's  all     folks   <tab separated>
    
    that's  all     folks   <space separated>
    

    Exampe Use/Output

    使用相同的输入文件,输出现在是:

    $ ./bin/gcfmt1 <dat/gcfmt.txt
    N <tab> description
    21 grapes
    18 pickles
    N <spaces> description
    23 apples
    51 banannas
    <spaces>N<tab> description
     8 cherries
     4 mellons
     6 strawberries
    that's all folks <tab separated>
    that's all folks <space separated>
    

    如果这是您的意图,请告诉我 .

相关问题