Q: 编写一个程序,从标准输入一行一行地读取文本,如果相邻出现重复内容,则打印出其中一行,其余的不打印.
程序具体要求:
如果文件中有2行或更多相邻的文本内容相同,那么久打印出其中一行,其余的行不打印。假设文件中文本行在长度上不会超过128个字符,(127个字符加上用于终结文本行的换行符)。
考虑下面的输入文件。
This is the first line.
Another line.
And another.
And another.
And another.
And another.
Still more.
Almost done now --
Almost done now --
Another line.
Still more.
Finished.
假设所有的行在尾部没有任何空白,程序应该输出:
And another.
Almost done now --
所有内容相同的相邻文本行有一行被打印,注意“Another line”和“Still more”并未打印,因为它们虽然各占2行,但相同文本行的位置并不相邻。
提示:使用gets函数读取行,使用strcpy函数来复制,使用strcmp函数进行比较。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *lastStr[128];
char *currentStr[128];
int theSameLineCount = 0;
while(gets(currentStr) != NULL) {
if (strcmp(lastStr, currentStr) == 0) {
theSameLineCount++;
} else {
if (theSameLineCount > 0) {
printf("\t>>>%s\n", lastStr);
}
theSameLineCount = 0;
}
strcpy(lastStr, currentStr);
printf("\t%d\n", theSameLineCount);
}
system("pause");
return 0;
}
测试的结果:
This is the first line.
0
Another line.
0
And another.
0
And another.
1
And another.
2
And another.
3
Still more.
>>>And another.
0
Almost done now --
0
Almost done now --
1
Another line.
>>>Almost done now --
0
Still more.
0
Finished.
0