简体   繁体   English

从C程序获取错误的输出

[英]Getting wrong output from c program

I'm new to C programming. 我是C编程新手。 I have written a program and I am getting the output 0 1 when 'a' is entered through the keyboard. 我已经编写了一个程序,当通过键盘输入“ a”时,输出为0 1 From what I know about the for loop, it should not execute the statements of the body if the condition becomes false . 根据我对for循环的了解,如果条件变为false ,则不应执行主体的语句。 So the output should be 0 when 'a' is entered. 因此,输入“ a”时输出应为0

#include<stdio.h>
main()
{   int c;

    long nc=0;
    for(nc=0;c=getchar()!=EOF;++nc)
    {
        printf("%ld \n",nc);
    }
}

You entered a then <return> , so 2 chars are available for input, 0 is written for the first and 1 for the second. 您输入a then <return> ,因此可以输入2个字符,第一个写入0 ,第二个写入1 Everything correct. 一切正确。

--EXPLANATION REQUESTED BY OP-- -OP要求的解释-

start with nc equals to 0, first call to getchar() reads a , nc equals to 0 then 0 is printed, nc incremented so now equals to 1; nc等于0开始,首先调用getchar()读取anc等于0然后打印0nc递增,因此现在等于1; then second call to getchar() reads newline , nc equals to 1 then 1 is printed, nc incremented so now equals to 2. 然后对getchar()第二次调用读取newlinenc等于1然后输出1nc递增,因此现在等于2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM