【问题标题】:Why is there no output and what is the value of EOF? [duplicate]为什么没有输出,EOF的值是多少? [复制]
【发布时间】:2019-04-26 23:45:59
【问题描述】:

我正在测试“C 编程语言”一书中的代码,我想知道 EOF 的价值是什么,我如何才能找到它?我尝试使用某种指针引用该值,但我只是得到一个 const 指针错误。无论如何,下面是我的代码,我想知道为什么点击回车后没有输出:

#include <stdio.h>

#define IN 1 /*inside a word*/
#define OUT 0 /*outside a word*/

/* count lines, words, and characters in input*/
main()
{
  int c, nl, nw, nc, state;

  state = OUT;

  nl = nw = nc = 0;
  while ((c = getchar()) != EOF){
    ++nc;
    if (c == '/n')
      ++nl;
    if (c == ' ' || c == '\n' || c == '\t')
      state = OUT;
    else if (state == OUT){
      state = IN;
      ++nw;
    }
  }
  printf("%D %D %D\n", nl, nw, nc);
}

【问题讨论】:

  • 您可以通过打印找到EOF 的值——printf("EOF = %d\n", EOF);——该值很可能是-1,但只能保证为负数。在 Windows 的终端上,您可以键入 control-Z 来指示 EOF;在 Unix 上,您需要输入 control-D。换行符(按“输入”的结果)不是 EOF。请注意,在 Unix 上键入 control-Z 可能会导致命令提示符,但程序会以暂停动画的状态放置在后台,因此在您将其带回前台之前它不会打印任何输出。查找“作业控制”以获取更多信息。
  • if (c == '/n') 看起来像是一个错字。 %D 看起来也像是一个错字。
  • 使用%D 不是标准的printf() 格式——C 是一种区分大小写的语言,格式字符串为printf()(和scanf(),以及它们的两个函数系列)区分大小写。你需要%d 三次。
  • 因为写一个好的答案比写冗长的 cmets 需要更长的时间——@Swordfish。代码中的问题比我在第一条评论中诊断的要多。此外,我应该寻找重复的,但这是一项吃力不讨好的任务,尤其是因为 SO 不会提供工具来帮助人们查找和保存重复记录。
  • 总是在启用警告的情况下编译,并且不要接受代码,直到它在没有警告的情况下干净地编译。如果你自己这样做,你 90% 的问题都会迎刃而解。

标签: c


【解决方案1】:
#include <stdio.h>

#define IN 1 /*inside a word*/
#define OUT 0 /*outside a word*/

/* count lines, words, and characters in input*/
int main(void)
{
  int c, nl, nw, nc, state;

  state = OUT;

  nl = nw = nc = 0;
  while ((c = getchar()) != EOF){
    ++nc;
    if (c == '\n')
      ++nl;
    if (c == ' ' || c == '\n' || c == '\t')
      state = OUT;
    else if (state == OUT){
      state = IN;
      ++nw;
    }
  }

  printf("%d %d %d\n", nl, nw, nc);
  printf("EOF = %d\n", EOF);
  return 0;
}


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 2012-12-21
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    相关资源
    最近更新 更多