replacing two newlines with a single newline

I'm trying to write a program for an assignment which takes standard input and writes only non-empty lines to standard output. I'm just having a little trouble working out how to do that. This is my code so far

#include <stdio>
int main( void )

#define MAX_CHAR 256
{
char c;
char line[MAX_CHAR];
int c_length = 0;

while(( c = getchar()) != EOF && c_length < MAX_CHAR - 1 ){

line[c_length] = c;
c_length++;

}
line[c_length] = 0
printf("%s", line);
return 0;
}

Any help would be appreciated. Even if you can just point me in the right direction.
just check if the c_lenght is greater than zero, then only do a printf.
I tried that but when I pass text though it still prints out empty lines.

If I use this code instead is there any way to not get it to putchar empty lines? I looked at if(isspace(c)) and others but nothing seems to do what I want

#include <stdio.h>
int main( void )
{
char c;
while( (c = getchar()) != EOF )
putchar( c );
}
Last edited on
What you are doing in the previous code is fine.

what I meant is

1
2
3
4
if(c_length)
{
printf("%s", line);
}


will this not work ?
use a for-loop to print it and check if each character is not a space before printing
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>

int main()
{
    std::string extracted ;

    while ( std::getline(std::cin, extracted) )
        if ( extracted.length() )
            std::cout << extracted << '\n' ;
}
So I have tried


#include <stdio>
int main( void )

#define MAX_CHAR 256
{
char c;
char line[MAX_CHAR];
int c_length = 0;

while(( c = getchar()) != EOF && c_length < MAX_CHAR - 1 ){

line[c_length] = c;
c_length++;

}
line[c_length] = 0
if(c_length)
{
printf("%s", line);
}
return 0;
}

and using

if(c_length > 0)
{
printf("%s", line);
}

but it is still printing lines.

it there anyway to take "\n\n" and replace it with "\n"?
Topic archived. No new replies allowed.