目的:从标准输入中读取输入的内容,以行为单位,当连续两行或更多行相同时,则打印出这一行的内容,其余行不打印,连续 出现的行只打印一次。假定文件长度不超过128个字符。
思路:首先读取两行标准输入,分辨保存为previous和current,然后比较两行是否相同(strcmp);若相同,则打印这一行;若不同,则将current copy给previous(strcpy),然后读取下一行,继续判断是否相同。
代码如下:
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define LIINE_SIZE 129
void pr_dup()
{
char previous[LIINE_SIZE], current[LIINE_SIZE];
if (gets(previous) != NULL)
{
while (gets(current) != NULL)
{
if (strcmp(current, previous) != 0)
{
strcpy(previous,current);
}
else if (! printed_from_group)
{
printf("continuous Line:%s\n",current);
}
}
}
}
输入
abc
abc
abc
def
adf
def
输出
abc
abc
continuous line:abc
abc
continuous line:abc
def
adf
def
这里有一个Bug,当连续三行一样的话,就会另外输出一个abc,而要达到的目的是只要连续相同的字符行,不管连续多少行,都只输出其中一行。那么就需要一个标志位告诉程序这一行已经被输出了,当后面两行还相同时,不要继续输出了。
修改之后的代码如下:
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define LIINE_SIZE 129
void pr_dup()
{
char previous[LIINE_SIZE], current[LIINE_SIZE];
int printed_from_group = FALSE; //标志位,当前行未被打印
if (gets(previous) != NULL)
{
while (gets(current) != NULL)
{
if (strcmp(current, previous) != 0) //若两行不同,则舍弃前一行,保存当前行,并将标志位 置false
{
strcpy(previous,current);
printed_from_group = FALSE;
}
else if (! printed_from_group) //若两行相同,则查看标志位,若未被打印,则打印当前行,并把标志位 置true
{
printf("continuous line:%s\n",current);
printed_from_group = TRUE;
}
}
}
}
实现功能时,先把最主要的核心功能实现,这个例子中就是先实现连续行可以打印,然后再完善成连续行只打印一次。