Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting an empty line in C

Tags:

c

string

parsing

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;
}
like image 842
johnny Avatar asked Nov 01 '22 04:11

johnny


1 Answers

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;
}
like image 149
QuestionC Avatar answered Nov 15 '22 05:11

QuestionC