I'm trying to look up for the most frequent word in a text. In my program, I input some words some texts. The words and texts are separate by "-----"(I need to search for the most frequent word in my program).
However, I found that when the program search for words in the text. It seemed that it can not run out of the loop(I got time limited exceeded on PC^2). Then, I found that the problem comes from this function(I got Wrong answer error if I annotate this function). Does I misunderstand the usage of scanf
or miss some other condition?
void inputTextTxt(void) {
for (;;) {
// toss all non-alpha-numerics
scanf("%*[^a-zA-Z0-9_]");
int cnt = scanf("%2047[a-zA-Z0-9_]", tmp);
if (cnt != 1) {
break; // or return
}
for (size_t i = 0; i < dic_actual_num; ++i) {
if (strcmp(dicWord[i], tmp) == 0) {
dicWcount[i]++;
}
}
}
}
- The character which is not digit, alphabet, and '_' should be treated as space
- The longest length of each line is 1024
Other parts of my code
char tmp[2048];
char **dicWord;
int *dicWcount;
int dic_assume_num = 1, dic_actual_num = 0;
void inputDicTxt() {
char divider[6] = "-----";
dicWord = malloc( dic_assume_num * sizeof( char* ));
for (;;) {
scanf("%*[^a-zA-Z0-9_-]");
int cnt_divider = scanf("%2047[-]", tmp);
int cnt_alphaNumerics = scanf("%2047[a-zA-Z0-9_]", tmp);
if (cnt_divider != 1 && cnt_alphaNumerics != 1)
break;
else if (cnt_divider) {
if (strcmp(tmp, divider) >= 0) {
dicWcount = calloc(dic_actual_num, sizeof(*dicWcount));
break;
}
}
else if (cnt_alphaNumerics) {
if (dic_actual_num >= dic_assume_num) {
dic_assume_num *= 2;
dicWord = realloc( dicWord, dic_assume_num * sizeof( char* ));
}
dicWord[dic_actual_num++] = strdup(tmp);
}
}
}
int main() {
inputDicTxt();
inputTextTxt();
int mostNum = 0;
for (int i = 0; i < dic_actual_num; ++i)
if (dicWcount[i] > dicWcount[mostNum])
mostNum = i;
// print out the most frequent word and its number
printf("%s %d\n", dicWord[mostNum], dicWcount[mostNum]);
for (int i = 0; i < dic_actual_num; ++i)
free(dicWord[i]);
free(dicWord);
free(dicWcount);
return 0;
}
EDIT: I've changed from while(feof(!stdin))
to for(;;)
in my code, but I still get TLE on the judging system