gpt4 book ai didi

c - 请解释一下这个...我被困住了

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

我已经开始做 C 语言,最近我开始做 Dennis Ritchie 和 Brian Kernighan 写的 C 编程书......我坚持练习 1.9“编写一个 C 程序以将其输入复制到它的输出,将一个或多个空格的每个字符串替换为一个空格”...我尝试了很多方法...查看互联网并找到了答案,但没有解释...我见过类似的代码

#include <stdio.h>
main()
{
int c, last;
last = EOF;
while ((c = getchar()) != EOF)
{
if (c != ' ')
putchar(c);
if (c == ' ')
{
if (last != ' ')
putchar(c);
}
last = c;
}
}

所以请有人解释一下,或者给我另一个带有正确解释的代码

谢谢

最佳答案

#include <stdio.h>
main()
{
int c, last;
last = EOF;

/* while we get a char that isn't EOF */
while ((c = getchar()) != EOF) {
/* if it's not a space, print it */
if (c != ' ')
putchar(c);
/* otherwise, if the previous char was not a space, print it */
if (c == ' ')
if (last != ' ')
putchar(c);
last = c;
}
}

这段代码可以更简单地写为

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

/* while we get a char that isn't EOF */
for (last = EOF; (c = getchar()) != EOF; last = c) {
/* if it's not a space, print it */
if (c != ' ')
putchar(c);
/* otherwise, if the previous char was not a space, print it */
else
if (last != ' ')
putchar(c);
}
}

关于c - 请解释一下这个...我被困住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34712600/

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