Reputation: 169
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;
}
Upvotes: 1
Views: 350
Reputation: 121387
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;
}
Upvotes: 2