一个小bug调试了很长时间,在判断title里面有没有对应的单词的时候,使用的是strstr函数,但是没有注意判断子串的前后是不是空格或是\0,太失败了,出这种傻逼的错,wrong了十几次,以后一定要小心了。
#include <stdio.h>
#include <string>
#include <string.h>
#include <set>
#include <algorithm>
#include <iostream>
using namespace std;
set<string> ignore_word;
set<string> key_word;
char buffer[1000];
char title[205][1000];
void print_result(int count)
{
//printf("result:\n");
int i, j;
set<string>::iterator it;
char temp[1000];
char title_temp[1000];
char *start;
bool f;
for(it=key_word.begin(); it!=key_word.end(); it++)
{
strcpy(temp, (char*)((*it).c_str()) );
for(i=0; i<count; i++)
{
strcpy(title_temp, title[i]);
start = title_temp;
f = false;
while(1)
{
if(*start == '\0')
break;
start = strstr(start, temp);
if(start == NULL)
break;
if(start-title_temp>=1 && start[-1]!=' ')
{
start ++;
continue;
}
if(start[strlen(temp)]!='\0' && start[strlen(temp)]!=' ')
{
start ++;
continue;
}
strcpy(title_temp, title[i]);
for(j=1; j<=strlen(temp); j++)
{
*start = *start + ('A'-'a');
start ++;
}
printf("%s\n", title_temp);
}
}
}
}
int main(void)
{
int i;
ignore_word.clear();
key_word.clear();
string str;
int start, end, count;
while(1)
{
fgets(buffer,1000,stdin);
buffer[strlen(buffer)-1] = '\0';
if(strcmp(buffer,"::"))
{
for(i=0; i<strlen(buffer); i++)
if(buffer[i]>='A' && buffer[i]<='Z')
buffer[i] = buffer[i] + ('a'-'A');
str.assign(buffer, strlen(buffer));
ignore_word.insert(str);
}
else
{
break;
}
}
/*
set<string>::iterator it;
printf("ignore word:\n");
for(it=ignore_word.begin(); it!=ignore_word.end(); it++)
{
cout << *it << endl;
}
*/
count = 0;
while(fgets(buffer,1000,stdin))
{
buffer[strlen(buffer)-1] = '\0';
/*
//这几行代码是测试用的,提交的时候要注释掉
if(!strcmp(buffer,"over"))
break;
*/
//所有字符全部换成小写
for(i=0; i<strlen(buffer); i++)
if(buffer[i]>='A' && buffer[i]<='Z')
buffer[i] += ('a'-'A');
strcpy(title[count++], buffer);
start = 0;
for(i=0; i<strlen(buffer); )
{
if(buffer[i]!=' ')
{
start = i;
}
else
{
i++;
continue;
}
for(end=start+1; end<strlen(buffer); end++)
if(buffer[end] == ' ')
break;
//保存关键词
str.assign(buffer+start, end-start);
if(ignore_word.find(str) == ignore_word.end())
{
//cout << "key word found:" << str << endl;
key_word.insert(str);
}
else
{
//cout << str << " is ignoreed!" << endl;
}
i = end;
}
}
/*
printf("keyword:\n");
for(it=key_word.begin(); it!=key_word.end(); it++)
{
cout << *it << endl;
}
*/
print_result(count);
return 0;
}