【问题标题】:Understanding an exercise in K&R [closed]了解 K&R 中的练习 [关闭]
【发布时间】:2013-12-14 22:20:53
【问题描述】:

这个程序是来自 K&R 书 The C Programming Language 的练习:

编写一个程序,将其输入复制到其输出,用一个空格替换每个包含一个或多个空格的字符串。

#include<stdio.h>
#define NONBLANK 'a'

int main(void)
{
      int c, lastc;

      lastc = NONBLANK;
      while ((c = getchar()) != EOF){
            if ( c != ' ')
                putchar(c);
            if ( c == ' ')
                if (lastc != ' ')
                    putchar(c);

            lastc = c;

            }
       } 
}

我只是想知道这个程序在无聊的细节中是如何运作的。

【问题讨论】:

  • 一步一步调试
  • 早点做作业。但是为什么不读这本书呢?
  • @EdHeal 不一定是功课,她会读 K&R。
  • 格式化文本更容易阅读。
  • 本身可能不是家庭作业。但是大多数(如果不是全部)书籍在章节末尾都有练习,以确保您理解该章节和前面的章节

标签: c unix ascii


【解决方案1】:

哼。锻炼 ?无聊的细节?

    #include<stdio.h>
    #define NONBLANK 'a'               /* a fake char to use later */
    main()
    {
      int c, lastc;

      lastc = NONBLANK;                /* now last c == char 'a' */
      while ((c = getchar()) != EOF){  /* parse input (stdin), char by char */
        if ( c != ' ')                 /* if the char is a *not* a space ..*/
        putchar(c);                    /* then write it on stdout; */
        if ( c == ' ')                 /* if it is a space ..*/
          if (lastc != ' ')            /*.. and lastc is *not* a space ..*/
            putchar(c);                /* then write it on stdout; */
        lastc = c;                     /* Make lastc be equal to the current */
                                       /* parsed char, and loop up to while */
      }
   }

PS:第一次在这里..抱歉格式混乱。

HTH

-- michel marcon(又名 cmic)

【讨论】:

    【解决方案2】:

    只要stdin 中的字符不是EOFwhile 循环就会继续执行:

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

    声明了两个char 变量:clastc。要使此逻辑起作用,必须知道当前字符和前一个字符。最初,lastc 没有值,但它仍然被使用:

    if(lastc != ' ')
        putchar(c);
    

    有可能在程序启动时lastc 会有一个垃圾值!= ' '。当您将其声明为合理的值时,定义此变量将是一个非常好的主意:

    int c, lastc = ' ';
    

    逻辑如下:

    stdin 读取当前字符。如果不是空格字符(' '),则写入stdout。如果是空格,则仅当前一个字符不是空格时,才会将空格写入stdout。如果前一个字符是空格,则忽略当前空格,如果stdin 中有一系列空格字符,则只打印一个空格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 2015-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多