getchar() in a for loop condition

时间:2016-10-15 17:19:37

标签: c for-loop getchar

Consider following code:

int main()
{
char c;
for(;(c=getchar())+1;)
    printf("%c\n",c);
}

It gets characters what I enter in terminal and prints them. When I remove +1 in condition, program works but it doesnt stop when EOF (Ctrl+D) signal. When I change it to +2 same problem.

My question is how that +1 work? Is it something related to getchar() or for loop?

3 个答案:

答案 0 :(得分:1)

That is because the int value of EOF is -1, so what you're doing is loop until the expression(c=getchar())+1) gets the value 0 which is when you read EOF (where value of exrpession is: -1+1=0). Also as wll pointed out in the comments you should declare c as int since getchar() returns int.

答案 1 :(得分:1)

for statement works with limits known already if you want a conditional loop use while :

int main()
{
int c;
while ((c=getchar()) != eof())
    printf("%c\n",c);
}

答案 2 :(得分:1)

仅适用于+1的原因。
原型:int getchar(void);

返回值

  • 成功时,返回字符读取(提升为int值)。

  • 返回类型为int以容纳特殊值EOF,表示失败(-1)。

  • 如果标准输入位于文件末尾,则该函数返回EOF并设置标准输出的eof指示符(feof)。

  • 如果发生其他一些读取错误,该函数也会返回EOF,但会设置其错误指示符(ferror)。