K&R Solutions - 1.18

Q: Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.

A:

#include <stdio.h>
#define MAXLINE 1000

int get_a_line(char s[], int lim);
void chop(char s[], int lim);

int main(void)
{
  int len;
  char line[MAXLINE];

  while ((len = get_a_line(line, MAXLINE)) > 0) {
    if (line[0] == '\n') {
      // Nothing happens. We want to totally ignore strings that are just
      // newlines.
    } else {
      chop(line, MAXLINE);
      printf("%s<---End Of String\n", line);
    }
  }

  return 0;
}

// Same as the previous exercise.
int get_a_line(char s[], int lim) 
{
  int c, i;

  for (i = 0; i < lim-1 && (c=getchar()) != EOF && c != '\n'; ++i) {
    s[i] = c;
  }
  if (c == '\n') {
    s[i] = c;
    ++i;
  }
  s[i] = '\0';
  
  return i;
}

void chop(char s[], int lim) {
  int i;

  // First we find the end of the string.
  // Notice that the the resulting value of 'i' is the length of the string.
  // Also notice that in this context, we could have just moved to the newline
  // before the null char.
  for (i = 0; s[i] != '\0'; ++i) {
  }

  // Now move backwards again, untill we find something that's not whitespace.
  for (i -= 1; s[i] == '\t' || s[i] == '\n' || s[i] == ' '; --i) {
  }

  // And we replace whatever is after with a null char.
  // We're replacing the newline, even though the exercise doesn't tell us
  // to get rid of it. This is becuse it makes the output easier to test.
  s[i+1] = '\0';
}
./trimmer
hi 	  (enter)
hi<---End Of String
how are         you?		(enter)	 
how are 	you?<---End Of String
(enter)
three little birds(enter)
three little birds<---End Of String