5

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;
}
2
  • 2
    Have a look at this question, might help you.
    – mattias
    May 7, 2015 at 20:30
  • How are you defining whitespace? Is SPACE a whitespace? What about TAB? BEL? ESC? Be careful with your definition of whitespace, look at asciitable.com to get a better picture of what I mean.
    – Eugene K
    May 7, 2015 at 20:54

3 Answers 3

1

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;
}
1

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").

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.