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

How can I stop a blank/tab from being outputted if there is a blank/tab before?


I’m using K&R’s “The C Programming Language” and was currently doing Exercise 1-12. The problem is not in resolving the exercise, but in trying to resolve one of the bugs that arise from it.

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, 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);
    }
    }
}

I’m starting to think that I’m not equipped to solve this "bug" with what I know. Maybe I need to store the input with extra blanks or tabs removed and then output the blanks or tabs with tabs. But that seems comboluted.



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