Your logic is correct, but your usage of feof() is not. According to this documentation, the EOF indicator is set after an attempt is made to read past the end-of-file. So your code sometimes does not detect the EOF and executes again on the last test case such as here. The correct way would be to check for EOF after a read operation, like this. This code gets accepted verdict.