K& R的C计划pg。 17行计数程序结果始终为0

时间:2014-10-03 01:09:59

标签: c

我一直在阅读K& R的The C Programming Language。当我输入第17页的示例程序来计算行数时,程序始终结果始终为0.这是我的代码:

/* Taken from The C Programming Language by Brian W. Kernighan and 
 * Dennis M. Ritchie */

/* Include statement added for compatibility */
#include "stdio.h"

main()    /* count lines in input */
{
  int c, nl;

  nl = 0;
  /* EOF in Linux is ctrl-D and ctrl-Z on Windows */
  while ((getchar()) != EOF)
    if (c == '\n')
      ++nl;
  printf("%d\n", nl);
}

1 个答案:

答案 0 :(得分:4)

while ((getchar()) != EOF)

应该是

while ((c = getchar()) != EOF)

你的书副本真的错了吗?我检查了我的,这是第二版,它有第19页的程序,而不是你的17,代码是正确的。

当您开始使用C编程时,为您带来巨大回报的东西是始终启用所有可用的编译器诊断。在这种情况下,gcc -Wall -Wextra -Werror拒绝编译此程序,说:

error: ‘c’ may be used uninitialized in this function [-Werror=uninitialized]
相关问题