【问题标题】:Why does moving printf() in a while loop that uses getchar() produce different results?为什么在使用 getchar() 的 while 循环中移动 printf() 会产生不同的结果?
【发布时间】:2019-02-01 22:27:10
【问题描述】:

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

我的代码有两个版本:

第一个:

#include <stdio.h>

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

当我输入 12 并按下返回键时,这会产生:

12
1 hello
2 hello

然后还有另一个我将 printf() 向上移动,输入相同的输入

#include <stdio.h>

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

它会产生:

12
1 hello
2 hello

 hello

为什么这两个不能以相同的方式工作,为什么额外的问候出现在第二个代码的末尾。

【问题讨论】:

标签: c


【解决方案1】:

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

第一个sn-p:

Read '1' -> 
Print '1' -> 
Read '2' -> 
Print "hello\n" -> 
Print '2' -> 
Read '\n' -> 
Print "hello\n" -> 
Print '\n' -> 
wait for more input

所以最后打印的是换行符。

第二次sn-p:

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"

简而言之,两个 sn-ps 执行相同数量的迭代,但在第一个中,当没有更多输入时,最后一个 printf(" hello\n")getchar 阻止。在第二个 sn-p 中不是这种情况。

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多