當前輸入字符可以分為兩種情況:
1、當前輸入字符不為空,則直接輸出這個字符即可;
2、當前輸入字符為空,這種情況又可以分為兩種情況:
①、上一個輸入字符也為空,則忽略此次輸入的空格即可;
②、上一個輸入字符不為空,則直接輸出這個字符即可。
基本思想是:
設置兩個變量,分別記錄當前輸入的字符和上一次輸入的字符,“上一個字符”初始化為EOF。
如果當前輸入字符為空,上一個輸入字符也為空,則忽略當前輸入的字符。

#include <stdio.h> main() { int c, pc; /* c = character, pr = previous character */ /* set pc to a value that wouldn't match any character, in case this program is over modified to get rid of multiples of other characters */ pc = EOF; while ((c = getchar()) != EOF) { if (c == ' ') if (pc != c) /* or if (pc != ' ') */ putchar(c); /* We haven't met 'else' yet, so we have to be a little clumey */ if (c != ' ') putchar(c); pc = c; } }

#include <stdio.h> main() { int c; /* 用於存放當前輸入的字符 */ int pc; /* 用於存放當前輸入的上一個字符 */ while((c = getchar()) != EOF) { if (c != ' ') { putchar(c); } else if (pc != ' ') { putchar(c); } pc = c; } }