Blank line detection in C

I am trying to keep line by line input by storing it in a line. I should be able to detect an empty line or a line consisting only of white spaces, and print "ignored" if this happens. How should I do it? strlen (str) == 0 does not seem to work.

int getLine(char str[]) {
  int i = 0;
  int c;
  while (i < N - 1 && (c = getchar()) != EOF && c != '\n') {
    str[i] = c;
    ++i;
  }
  if (c == EOF) return 0;
  str[i] = '\0';
  return 1;
}
+4
source share
3 answers

New Feature:

int getNonBlankLine(char str[])
{
    int nb = 0;
    while (nb == 0)
    {
        int i = 0;
        int c;
        while (i < N - 1 && (c = getchar()) != EOF && c != '\n')
        {
            str[i++] = c;
            if (!isblank(c))
              nb++;
        }
    }
    if (c == EOF)
        return 0;
    str[i] = '\0';
    return i;
}

This returns the length of the string; it excludes a new line from the returned data; it skips all empty lines; it does not overflow its buffer; it does not give you the opportunity to detect that the string does not all fit into the buffer.

, . , .

isblank(), , isspace(), , , , , (" \t\n\f\r\v").

+1

strlen , , . :

int all_space(const char *str) {
    while (*str) {
        if (!isspace(*str++)) {
            return 0;
        }
    }
    return 1;
}
0

A line containing only spaces is not empty. It is filled with spaces.

There are several ways to do this. Hope this is clear.

// Returns nonzero iff line is a string containing only whitespace (or is empty)
int isBlank (char const * line)
{
  char * ch;
  is_blank = -1;

  // Iterate through each character.
  for (ch = line; *ch != '\0'; ++ch)
  {
    if (!isspace(*ch))
    {
      // Found a non-whitespace character.
      is_blank = 0;
      break;
    }
  }

  return is_blank;
}
0
source

All Articles