开发者

How do i compress blank lines

开发者 https://www.devze.com 2023-03-13 09:15 出处:网络
I am trying to find a way to compress blank lines. My current code does it for the middle part, but at the beginning it does not compress the blank lines.

I am trying to find a way to compress blank lines. My current code does it for the middle part, but at the beginning it does not compress the blank lines.

CODE:

#include<stdio.h>
#include<string.h>
#include<ctype.h>

int main (void)
{   
int c, space = 0, newline = 0;

/*reads char by char til EOF*/
while((c = getchar()) != EOF)
{

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

    if(c == ' ')
    {
        if(space == 0)
        {
            putchar(' ');
            space = 1;
        }
    }
    else if(c == '\n')
    {
        newline++;

        if(newline <= 2)
        {
            putchar('\n');
        }

    }
    else
    {
        if(space == 1)
        {
            space = 0;
        }

        if(c != '\n')
        {
            newline = 0;
        }

        putchar(c);
    }
}

return 0;
}

Say that i input:

[开发者_C百科BLANK] [BLANK] [BLANK] test [BLANK] [BLANK] [BLANK]

I want the output the be: [BLANK] test [BLANK]

How do i change my code so that it outputs the right thing.

Thanks in advance

PS: I'm using I/O redirection to test it.

EDIT: Forgot to mention that i use linux text files so it gets rid of the /r

EDIT 2: I've uploaded the output file here:

http://www.mediafire.com/?gtbjctbn2jjaxdo


Sometimes files use \r\n instead of \n, So, you'll want to exclude \r.


I don't understand what you're trying to do with

if(newline <= 2)
{
    putchar('\n');
}

The first, second, and third times you see a new line, you put a new line. Of course [BLANK][BLANK][BLANK]thing becomes [BLANK][BLANK][BLANK]thing.

You should try re-writing this as a state machine: it will be more clear what you are trying to do, and it will be more clear to you what you need to do when you see each character.

Further, consider using a switch statement instead of all the ifs.

0

精彩评论

暂无评论...
验证码 换一张
取 消