0

I'm trying to write code that registers the first word of every line as a command, but I want to be able to read the word regardless of there being spaces or not in front of it. I'm currently using fgets() and strncmp the first x characters of each line to do this, but it doesn't work for an arbitrary amount of whitespace. I have tried using sscanf() inside the fgets() loop to store the first word of each line to a variable but it seems to be skipping through lines and reading them incorrectly. I would rather not post the code as it is quite lengthy but it is basically this:

while( fgets(Line, BUFFER, input) != NULL )
{
if(strncmp(Line, "Word", 4) != NULL)
//DO SOMETHING
}

There are many strncmps and I would like for each of them to ignore an arbitrary amount of preceding spaces.

John
  • 11
  • 1
  • 3

1 Answers1

3

You can use isspace to skip over whitespace:

#include <ctype.h>

while( fgets(Line, BUFFER, input) != NULL )
{
  char *p = Line;
  while (isspace(*p)) // skip whitespace
    p++;
  if(strncmp(p, "Word", 4) != NULL)
  //DO SOMETHING
}
perreal
  • 94,503
  • 21
  • 155
  • 181
  • I'm not sure if incrementing just Line is possible is it? I'm getting an error lvalue required as increment operand. – John Mar 10 '12 at 02:08
  • I've been at this for such a long time. I've actually come across this function but apparently made a simple mistake trying to implement and dismissed it. Thanks so much. This is really perfect. – John Mar 10 '12 at 02:15