首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

c程序设计语言上的练习题答案有些不懂,希望大家帮忙讲解下

2013-03-27 
c程序设计语言上的习题答案有些不懂,希望大家帮忙讲解下。#include stdio.hint main(void){int blanks, t

c程序设计语言上的习题答案有些不懂,希望大家帮忙讲解下。

#include <stdio.h>



int main(void)

{

  int blanks, tabs, newlines;

  int c;

  int done = 0;

  int lastchar = 0;



  blanks = 0;

  tabs = 0;

  newlines = 0;



  while(done == 0)

  {

    c = getchar();



    if(c == ' ')

      ++blanks;



    if(c == '\t')

      ++tabs;



    if(c == '\n')

      ++newlines;



    if(c == EOF)

    {

      if(lastchar != '\n')

      {

        ++newlines; /* this is a bit of a semantic stretch, but it copes

                     * with implementations where a text file might not

                     * end with a newline. Thanks to Jim Stad for pointing

                     * this out.  

                     */

      }

      done = 1;

    }

    lastchar = c;

  }



  printf("Blanks: %d\nTabs: %d\nLines: %d\n", blanks, tabs, newlines);

  return 0;




 if(c == EOF)

    {
        if(lastchar != '\n')   …
这一部分都不是很明白 好像直接用while((c=getchar())!=EOF)判读的话,按回车键,就直接输出了。但是这里不会。但是不知道为什么。希望大家指点下。谢谢了。
c语言,求助, EOF c程序设计语言
[解决办法]
    if(c == '\n')
 
      ++newlines;
回车在这里判断啦!
[解决办法]
你的写法更简洁。

引用:
我弄错问题的所在了  这是c程序设计语言习题对应的答案,我不是很明白那个为什么不直接用while((c=getchar())!=EOF)  这样不简单一些吗  为什么要这样写啊   那段英文注解也不是很明白

引用:而Windows中,在新的一行(输入enter迫使输出"标准输入"缓存区之后)开头按下Ctrl-Z表示EOF;如果真的想输……

[解决办法]

你的写法更简洁 ,这样写就是为了下面的记录newlines变量的判断,当写完一行换行再输入文件结束标志时正确统计出写入的行数。
 if(c == EOF)


 
    {
 
      if(lastchar != '\n')
 
      {
 
        ++newlines; /* this is a bit of a semantic stretch, but it copes
 
                     * with implementations where a text file might not
 
                     * end with a newline. Thanks to Jim Stad for pointing
 
                     * this out.  
 
                     */
 
      }
 
      done = 1;
 
    }


[解决办法]
这里的EOF 是end of file 意思在windows下按CTRL+Z键表示EOF,Linux下按CTRL+D键表示EOF,然后就会有输出了
[解决办法]
仔细看一下注释,原书是你的写法,但后来Jim Stad 发现了在有的操作系统中,其尾行并非以 newline 结尾。为此专门置信给k&R, 将程序改为如此,天下并非只有 windows

热点排行