gpt4 book ai didi

C中的字符计数

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:43 24 4
gpt4 key购买 nike

在下面的程序中,我试图计算一行中的字符数

#include <stdio.h>
/* count characters in input; 1st version */

int main()
{
double nc;

for (nc = 0; getchar() != EOF; ++nc)
;
printf("%.0f\n", nc);
}

但是线printf("%.0f\n", nc)没有被执行结果是这样的:

hello     
world

最佳答案

EOF 只是文件 的结尾,不是行尾。参见 the documentation .因此,当您按下回车键时,您的程序将停留在 for 循环中。您可以通过以下两种方式之一解决此问题:

  • 实际发送您的程序 EOF(在大多数基于 *nix 的系统上为 Ctrl-D),或者
  • 检查换行符而不是 EOF

试试这个:

  for (nc = 0; getchar() != '\n'; ++nc)

请注意,您的代码将在您发送第一个换行符后退出。

关于C中的字符计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25492725/

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