简体   繁体   中英

How to replace multiple blank lines with a single line in C language

I want to squeeze multiple lines in a single line. I have tried to apply my own logic but there is something wrong.

 char *p;
                    linecount=0;
                    while (fgets(buffer, sizeof(buffer), file))
                    {

                    //it will print the user input with number
                    p=buffer;

                    if('\r' == *p ||'\n' == *p )
                    {

                        linecount++;
                       if(linecount>2 )
                        printf("\n");
                    }

                    else
                    {
                        linecount=0;
                             printf("\t %s", p);

                    }

For instance a file has lines like

a
b


c


d
e

then the output should be

a
b

c

d
e

Basically, I am devloping a code for cat -s command.

In your if block:

if(linecount>2 )
    printf("\n");

What you are doing is printing out the 3rd, 4th, ..Nth blank lines.

The first blank like will have linecount = 1

The second blank like will have linecount = 2

I would reverse that logic to have

if( linecount == 0 ){
    linecount++;
    printf("\n");
}

This way, you will only print out the first blank line in the list of newlines.

Why are you using fgets? (And more importantly, why are you not handling lines that are larger than your buffer?) You only need to look at one character at a time:

#include <stdio.h>

int main(void) {
    int c;
    int count=0;
    while((c=getchar())!=EOF) {
        if(c=='\n'){
            if(++count>2)
              continue;
        } else {
            count=0;
        }
        putchar(c);
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM