how to input /n on a program that uses getchar() (and other confusion)

79 Views Asked by At

This is a pretty loosely fitting title I'll admit.

I'm doing an exercise where we are tasked with creating a program that removes trailing whitespace and deletes blank lines. One of the solutions posted online received praise but, when I run the code, it doesn't even seem like it does anything. Here is the solution I'm referring to, with a brief excerpt that I'm confused by

The program specification is ambiguous: does "entirely blank lines"
mean lines that contain no characters other than newline, or does it include lines composed of blanks and tabs followed by newline? The latter interpretation is taken here.

So he's saying that the code should be removing blank lines but I don't think it does, at least not when I run it. And I don't know how you would enter a new line as input because when you press enter it doesn't skip a line, it takes your input and continues to run the program. He goes on to mention "blanks and tabs followed by a newline" but again...what is newline when enter just runs the program? And if you try to leave lines blank just by pressing a tab or space a bunch, the program doesn't delete those lines, it prints out the same blank line, so I really don't know what his program is doing or what he's talking about.

#include <stdio.h>
#include <stdlib.h>

#define MAXQUEUE 1001

int advance(int pointer)
{
  if (pointer < MAXQUEUE - 1)
    return pointer + 1;
  else
    return 0;
}

int main(void)
{
  char blank[MAXQUEUE];
  int head, tail;
  int nonspace;
  int retval;
  int c;

  retval = nonspace = head = tail = 0;
  while ((c = getchar()) != EOF) {
    if (c == '\n') {
      head = tail = 0;
      if (nonspace)
        putchar('\n');
      nonspace = 0;
    }
    else if (c == ' ' || c == '\t') {
      if (advance(head) == tail) {
        putchar(blank[tail]);
        tail = advance(tail);
        nonspace = 1;
        retval = EXIT_FAILURE;
      }

      blank[head] = c;
      head = advance(head);
    }
    else {
      while (head != tail) {
        putchar(blank[tail]);
        tail = advance(tail);
      }
      putchar(c);
      nonspace = 1;
    }
  }
  return retval;
}

Apart from running the code, I've also stepped through it with the debugger and I find it kind of confusing but I don't even want to get into that until I can figure out what it's even trying to accomplish or why it's being praised when it seemingly doesn't accomplish anything.

0

There are 0 best solutions below