计算文本中各个单词的字数并输出(代码我重写了一遍,但发现执行后会输出乱码,请问怎么回事?代码在六楼)
执行后发现每次只能输出两个词,不知为啥??帮忙看看。 谢谢程序代码:
#include<string.h> #include<stdio.h> #include<stdbool.h> #define TEXT_LEN 10000 //maximum length of the text #define BUF_LEN 100 //the maximum length of each time of input #define WORDS_MAX 500 //there are at most 500 words #define WORDS_LEN 12 //length of each word should smaller than 12 int main() { char delimiters[]=" \n,.?;!"; char text[TEXT_LEN]; //store the whole text char buf[BUF_LEN]; //store one input line char words[WORDS_MAX][WORDS_LEN]; //store all the words int nword[WORDS_MAX]={0}; //store the number of words occurrences int word_count=0; //the number of words printf("please enter strings.Enter an empty line to end input\n"); //start to input........ while(1) { fgets(buf,BUF_LEN,stdin); if(buf[0]=='\n') break; if(!strcat(text,buf)) { printf("error!!!\n");break; } } char *pword=strtok(text,delimiters); if(!pword) { printf("there is no word\n");return 1; } strcpy(words[word_count],pword); ++nword[word_count++]; bool new_word=true; //找到的单词已存在words中就是false否则就是true while(true) { pword=strtok(NULL,delimiters); if(!pword) break; for(int i=0;i<word_count;i++) //old word if(strcmp(words[i],pword)==0) { nword[i]++; new_word=false; } if(new_word) //new word { strcpy(words[word_count],pword); ++nword[word_count++]; } else new_word=true; if(word_count>WORDS_MAX) { printf("there are too many words"); return 1; } //list all the words for(int i=0;i<word_count;i++) { printf("%-13s %3d ",words[i],nword[i]); if((i+1)%2==0) printf("\n"); } printf("\n"); return 1; } }
[此贴子已经被作者于2016-8-3 17:44编辑过]