gpt4 book ai didi

c - while ((ch = getchar()) != EOF) 或提前声明 int ch = getchar()

转载 作者:行者123 更新时间:2023-11-30 20:03:20 26 4
gpt4 key购买 nike

我在关注《C Primer Plus》这本书,遇到这样一段代码:

// echo_eof.c -- repeats input to end of file.
#include <stdio.h>
int main(void)
{
int ch;

while ((ch = getchar()) != EOF)
putchar(ch);

return 0;
}

输出:

$ ./a.out
She walks in beauty, like the night
She walks in beauty, like the night
Of cloudless, climes and starry skies...
Of cloudless, climes and starry skies...
Lord Byron
Lord Byron
^D

尽管如此,我发现 while ((ch = getchar()) != EOF) 内的嵌套括号并不吸引眼球。所以,我将其更改为:

// echo_eof.c -- repeats input to end of file.
#include <stdio.h>
int main(void)
{
int ch = getchar();

while (ch!= EOF)
putchar(ch);

return 0;
}

然而,它是无限的S

$ ./a.out
She walks in beauty, like the night
SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS.....

我重构的代码有什么问题?

最佳答案

在 while 循环之前,您只能获取 char 一次。char 指针永远不会递增,因此它永远不会达到 EOF。

出于好奇,您是否一直在使用其他语言(例如 Python),其中的方法可以轻松分配给变量?在 C 中有点棘手,你需要使用指针:

int (*ch)(); // Creates a function pointer
ch = getchar; //Then assign your getchar() function to it, without the brackets
while ((*ch)() != EOF) // Dereference and call your function

关于c - while ((ch = getchar()) != EOF) 或提前声明 int ch = getchar(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52827548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com