October 21, 2024
Chicago 12, Melborne City, USA
C#

How to Prevent Blank Lines and Remove Extra Spaces in C Word-per-Line Output?


I’m reading K&R’s The C Programming Language and currently working on Exercise 1-12. The issue I’m facing isn’t with completing the exercise itself, but with fixing a bug that has come up as a result of my code.

The code produces an unwanted blank line when encountering two or more spaces. I want to ensure that the output has no blank lines and that extra spaces are trimmed.

My solution.

#include <stdio.h>

int main(void)
{
    int c;
    
    while ((c = getchar()) != EOF)
    {
        if (c == ' ' || c == '\t')
        {
            printf("\n");
        }
        else
        {
            putchar(c);
        }
    }
}

Problematic output

bash >>> ./Exercises/ex12
hello  everyone
hello
 
everyone

I tried solving it based on Ex 1-9 [2], but no luck.

#include <stdio.h>
#define PREVCHAR 'a'

int main(void)
{
    int c, prevc = PREVCHAR;
    
    while ((c = getchar()) != EOF)
    {
        if (c == ' ' && prevc == ' ')
        {
            printf("");
        } else if (c == ' ' && prevc != ' ')
        {
            printf("\n");
        } else
        {
            putchar(c);
            prevc = c;
        }
    }
}

[1] = Write a program that prints its input one word per line.

[2] = Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video