关于重复调用一个嵌套函数的问题
就是做一个简单的计算一篇文章出现某个单词的个数,因为实在太菜了,虽然调试没问题,但程序却运行不起来,搞了好久都不知道问题出在哪里【程序1】
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define N 200
#define M 20
static int sum=0; /*sum是用来记录目标单词总共出现的次数,必须用static型*/
/************************************************************/
/*sum是用来记录目标单词总共出现的次数,必须用static型*/
void checkword(char* p1,char* objectword){
char temp[M];/*这个数组是用来存取从句子中提取出来的单词*/
int i=0,j,count=0;
while(p1[i]!='\0'){
j=0;
while(isalpha(p1[i])){/*用来检测p1[i]是不是字母*/
temp[j]=p1[i];
i++;
j++;
}
temp[j]='\0';
if(strcmp(temp,objectword)==0)/*判断提取出来的单词是否与要查找的单词一致*/
count++;
while(!isalpha(p1[i])&&p1[i]!='\0'){
i++;
}
}
if(count!=0){
printf("%s\n",p1);
sum+=count;
}
}
void getsentence(char* p1,FILE* p2,char* objectword){
int i;
char ch;
ch=fgetc(p2);
while(ch!=EOF){
i=0;
while(ch!='.'&&ch!=';'&&ch!=EOF){
p1[i]=ch;
i++;
ch=fgetc(p2);
}
if(ch=='.'||ch==';'){
p1[i]=ch;
p1[i+1]='\0';
checkword(p1,objectword);
ch=fgetc(p2);
}
}
}
/*******************************************************************/
int main()
{
char str1[M];
char str2[2][M];
char filename[M];
int m;
FILE* fp;
printf("Please input the name of the file:\n");
scanf("%s",filename);
printf("\n");
printf("Please input the word which you want to search:\n");
scanf("%s %s %s",str2[0],str2[1],str2[2]);
fp=fopen(filename,"r");
if(fp==NULL){
printf("cannot open the file\n");
exit(0);
}
for(m=0;m<=2;m++)
{ getsentence(str1,fp,str2[m]);
printf("The word %s which you want to search in the file have been appeared %d times in total!\n",str2[m],sum);}
fclose(fp);
system("pause");
return 0;
}
最后附一个需要打开的文件[local]2[/local]希望有人能指点一下在下。
顺问一下,如果将【程序1】的主函数改成如下:
int main()
{
char str1[M];
char str2[M][M];
char filename[M];
int m;
static n=0;
char ack;
FILE* fp;
printf("Please input the name of the file:\n");
scanf("%s",filename);
printf("\n");
for(m=0;;)
{
printf("Please input the word which you want to search:\n");
scanf("%s",str2[m]);
printf("another word(y/n)?\n");
scanf("%c",&ack);
printf("\n");
if (ack=='y')m++;
else
{n=m; /*n=m-1个要搜索的单词*/
break;}
}/*返回循环*/
fp=fopen(filename,"r");
if(fp==NULL){
printf("cannot open the file\n");
exit(0);
}
for ( m=0;m<=n;m++)
{
getsentence(str1,fp,str2[m]);
if (m==n)
printf("The word %s which you want to search in the file have been appeared %d times in total!\n",str2[m],sum);}
fclose(fp);
system("pause");
return 0;
}
原先我是希望实现无论输入多少个目标单词都能够可以计算其出现的次数【程序如上】,但因为程序不成功只好改成第一个程序,【限定了输入目标单词的个数】。请问我第二个主函数什么地方出错了?