Alexandr Ushakov Alexandr Ushakov - 1 month ago 12
C Question

c - why switch couldnt catch EOF (using getchar())?

#include "stdio.h"

int main() {
int wordsAmount = 0;
for(int c = 0, inWord = 0; ((c = getchar()) != EOF) ;) {
switch(c) {
case '\t' : inWord = 0; break;
case '\n' : inWord = 0; break;
case ' ' : inWord = 0; break;
case EOF : printf("\nwords amount: %d\n", wordsAmount); return 0;
default : if(inWord == 0) { wordsAmount++; inWord = 1; }
}
}

return 1;
}


This must count words, but it doesn't work.

Yes, if move EOF case body out from cycle, it should work, but how make it work in
switch
?

Answer

As mentioned by BLUEPIXY in comment section, because of ((c = getchar()) != EOF) the for loop condition will fail at EOF, So control will not go inside of your for loop.