c - 了解 K&R 中的练习

标签 c unix ascii

该程序是 K&R 书籍《C 编程语言》中的练习:

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

#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;

            }
       } 
}

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

最佳答案

嗯。锻炼 ?无聊的细节?

    #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

-- 米歇尔·马尔孔(又名 cmic)

关于c - 了解 K&R 中的练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20588913/

相关文章:

c - 如何将空格字符添加到字符串/字符数组?

c - C:free():下一个大小无效(快速)

linux - Linux中的自定义用户和自定义权限

linux - 当父进程有很多线程、套接字和 IPC 时,在派生(子)进程中调用 system()

python - 如何将带有斯堪的纳维亚字符的 UTF 字符串转换为 ASCII?

无法定义共享内存对象的大小

c - 编写一个 C 程序,读取 5 个数字并计算正数的个数并打印所有正数的平均值

bash - shell 管道的惰性(非缓冲)处理

javascript - 为什么 'a' > 'A' 是真的?

python - Django 问题 : UnicodeEncodeError