Parsing a text file - any reason why space / new line would be ignored?

时间:2016-02-03 04:10:42

标签: c

I have this while loop...

char count[3] = {0};
int i = 0;

while( c != ' ' || c != '\n' || c != '\t' ) {
    count[i] = c;
    c = fgetc(fp);
    i++;    
}

And even though I see while debugging that space and newline are the right ASCII numbers, the while loop does not exit. Anyone know what could be causing this?

1 个答案:

答案 0 :(得分:5)

The logic in the conditional is not right. It will evaluate to true all the time.

while( c != ' ' || c != '\n' || c != '\t' )

If c is equal to ' ' it is not equal to '\n' or '\t'.

What you probably need is:

while( c != ' ' && c != '\n' && c != '\t' )

And for good measure, I would also add c != EOF.

while( c != ' ' && c != '\n' && c != '\t' && c != EOF )

It might be simpler to use:

while( !isspace(c) && c != EOF )