johnny
johnny

Reputation: 81

Detecting an empty line in C

I'm trying to save input line by line storing it in a string. I need to be able to detect an empty line or a line that consists only of white spaces and print "ignored" if it happens. How do I do that? strlen(str) == 0 doesn't 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;
}

Upvotes: 5

Views: 14839

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 754450

New function:

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 line; it excludes the newline from the data returned; it skips over all blank lines; it doesn't overflow its buffer; it doesn't give you a way to detect that the line did not all fit in the buffer.

If you don't want to use a new function or add the code in the function above in place of your old function body, then you have to analyze the line after it is read and call the input again. Other answers give you code that can be used for that.

You can also choose between isblank() which recognizes blanks and tabs, and isspace() which recognizes blanks, tabs, newlines, formfeeds, carriage returns and vertical tabs (" \t\n\f\r\v").

Upvotes: 1

QuestionC
QuestionC

Reputation: 10064

A line that contains only spaces is not empty. It's full of spaces.

There's a number of ways to do this. Hopefully 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;
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

strlen will detect empty lines, but it would not detect lines consisting entirely of whitespace. You can write this function yourself:

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

Upvotes: 0

Related Questions