Testing getchar() == EOF doesn't work as expected

不羁岁月 提交于 2019-12-01 11:22:05

The getchar() call reads (and effectively discards) the first digit because it is not EOF.

You don't test that scanf() worked; you should.

for (i = 0; i < MAX; i++)
{
    if (scanf("%d", &x[i]) != 1)
        break;
}

At this point, there are i integers in the array; you don't really need to set iMax in the loop. You could simply set it when the loop exits.

Also, in addition to checking scanf, here is what you need to know:-

EOF is not a character. The EOF is a macro that getchar() returns when it reaches the end of input or encounters some kind of error. The ^D is not "an EOF character". What's happening under linux when you hit ^D on a line by itself is that it closes the stream, and the getchar() call reaches the end of input and returns the EOF macro. If you type ^D somewhere in the middle of a line, the stream isn't closed, so getchar() returns values that it read and your loop doesn't exit.

see http://www.c-faq.com/stdio/getcharc.html for a nice description.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!