Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在使用getchar()的while循环中移动printf()会产生不同的结果?_C - Fatal编程技术网

为什么在使用getchar()的while循环中移动printf()会产生不同的结果?

为什么在使用getchar()的while循环中移动printf()会产生不同的结果?,c,C,我是C新手,如果这个问题是基本的,我很抱歉。我试图理解getchar()函数的行为 这里我有两个版本的代码: 第一个: #include <stdio.h> int main() { int c = getchar(); while (c != EOF) { putchar(c); c = getchar(); printf(" hello\n"); } } 还有一个,我向上移动printf(),输入

我是C新手,如果这个问题是基本的,我很抱歉。我试图理解
getchar()
函数的行为

这里我有两个版本的代码:

第一个:

#include <stdio.h>

int main()
{
    int c = getchar();
    while (c != EOF)
    {
        putchar(c);
        c = getchar();
        printf(" hello\n");
    }
}
还有一个,我向上移动printf(),输入相同的输入

#include <stdio.h>

int main()
{
    int c = getchar();
    while (c != EOF)
    {
        putchar(c);
        printf(" hello\n");
        c = getchar();
    }
}

为什么这两个字符的工作方式不一样,为什么在第二个代码的末尾会出现额外的hello。

注意,您提供了一个3个字符的输入-
'1',2'
和一个换行符(
\n
)。 鉴于此,让我们跟踪您的程序正在执行的操作:

第一段:

Read '1' -> 
Print '1' -> 
Read '2' -> 
Print "hello\n" -> 
Print '2' -> 
Read '\n' -> 
Print "hello\n" -> 
Print '\n' -> 
wait for more input
所以最后印刷的是新线

第二段:

Read '1' -> 
Print '1' ->  
Print "hello\n" -> 
Read '2' -> 
Print '2' -> 
Print "hello\n" -> 
Read '\n' -> 
Print '\n' -> 
Print "hello\n" -> 
wait for more input.
因此,它首先打印新行,然后
“hello”


简而言之,两个代码段执行的迭代次数相同,但在第一个代码段中,最后一个
printf(“hello\n”)
在没有更多输入时被
getchar
阻止。第二段中的情况并非如此。

尝试将其更改为
printf(“hello%d\n”,c)可能重复的
Read '1' -> 
Print '1' -> 
Read '2' -> 
Print "hello\n" -> 
Print '2' -> 
Read '\n' -> 
Print "hello\n" -> 
Print '\n' -> 
wait for more input
Read '1' -> 
Print '1' ->  
Print "hello\n" -> 
Read '2' -> 
Print '2' -> 
Print "hello\n" -> 
Read '\n' -> 
Print '\n' -> 
Print "hello\n" -> 
wait for more input.