1

I have a code to read a line from a file input. My goal is if a line is a blank (either, \n \t or spaces), skip the line and continue to the next line. I have a problem on doing this. My code worked if the line is only an "enter key [\n]", however, if the line consists of just \t (tab) or spaces, it does not work. Here is the code. Can somebody help me how to ignore if the line is completely whitespaces? Thank you

while(!feof(input)){

    fgets(word,1000,input);

    if((strcmp(word,"\n")==0) || (strcmp(word,"\t\n")==0) || (strcmp(word," \n")==0)){
        continue;
    }
BoJack Horseman
  • 159
  • 5
  • 15

2 Answers2

2

You can use isspace() in loop:

int is_whitespace(char *word) {
   size_t spaces = 0;
   size_t i = 0;
   size_t slen = strlen(word);

   for (i = 0; i< slen; i++)
       if ( isspace((int)word[i]) ) spaces++;

   return spaces == slen;
}

and then you would be able to:

while( fgets(word,1000,input) ) {

    if (is_whitespace(word)) 
       continue;
}

Also, the loop condition is wrong. See Why is “while ( !feof (file) )” always wrong?


As suggusted by @chux, it can be simplified and the call to strlen() can be avoided:

int is_whitespace(char *word) { 

   while (isspace((unsigned char) *word))
     word++; 

   return *word == 0;
   }
Community
  • 1
  • 1
P.P
  • 117,907
  • 20
  • 175
  • 238
  • Yes. It includes all the whitespaces. Manual says: *checks for white-space characters. In the "C" and "POSIX" locales, these are: space, form-feed ('\f'), newline ('\n'), carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v').* – P.P Nov 29 '15 at 18:31
  • Sorry @blue Moon but it still ignores the line that only consists of \t (tabs) – BoJack Horseman Nov 29 '15 at 18:37
  • It worked now! thanks. I forgot to exclude the return statement in the for loop. Thank you! – BoJack Horseman Nov 29 '15 at 18:38
  • Could simplify to `int is_whitespace(char *word) { while (isspace((unsigned char) *word)) word++; return *word == 0;`. BTW `(int)` serves no value. – chux - Reinstate Monica Nov 29 '15 at 18:39
  • 1
    @chux Yes, that looks simpler, avoiding the call to strlen(). – P.P Nov 29 '15 at 18:42
1
char ch;
if(1 != sscanf(word, " %c", &ch)){
    continue;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70