用c语言编写输入一段英文,1 统计这段英文的单词数2 输入特定单词,统计本单词在上述英文中出现的次数 5
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * getword(FILE *fp);
int main()
{
puts("输入一段英文:");
FILE *fp;
if((fp=fopen("en.txt","w"))==NULL) { puts(" can't write ! ");exit(1);}
char words[2000],word[50],search[50];
gets(words);
fputs(words,fp);
fclose(fp);
if((fp=fopen("en.txt","r"))==NULL) { puts(" can't write ! ");exit(1);}
int num=0;
while(1)
{
strcpy(word,getword(fp));
if(strcmp(word,"")==0) break;
else num++;
}
printf("此段英文的单词个数为:%d\n",num);
printf("请输入你要查找的单词\n");
gets(search);
num=0;
rewind(fp);
while(1)
{
strcpy(word,getword(fp));
if(strcmp(word,"")==0) break;
else if(strcmp(word,search)==0) num++;
}
printf("此段英文中该单词 %s 个数为:%d\n",search,num);
fclose(fp);
remove("en.txt");
return 0;
}
char * getword(FILE *fp)
{
char f,word[50];
do{
int flag=0,i=0;
while(flag==0)
{
f=fgetc(fp);
if((f>='a'&&f<='z')||(f>='A'&&f<='Z')) word[i++] =f;
else flag=1;
}
word[i]='\0';
if(f==EOF) break;;
}while(word[0]=='\0');
return word;
}
你好,,可以改改吗?现在程序不区分大小写,比如文本里有And 和and两个单词,我查and出现的次数,应该是2,但现在的程序是1.。。然后,能不能把输入文本时改成以#号结尾。。谢谢
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
char * getword(FILE *fp);
int main()
{
puts("输入一段英文:'#'结束");
FILE *fp;
if((fp=fopen("en.txt","w"))==NULL) { puts(" can't write ! ");exit(1);}
char words[2000],word[50],search[50],save[50],f;
int k=0;
while(1)
{
if((f=getche())!='#') words[k++]=f;
else{ words[k]='\0';break;}
}
while(1)
{
strcpy(word,getword(fp));
if(strcmp(word,"")==0) break;
else
{
if(strcmp(word,search)==0) num++;
else
{
if('A'<=search[0]&&search[0]<='Z')
{search[0]+=32 ; if(strcmp(word,search)==0) num++;}
if('a'<=search[0]&&search[0]<='z')
{ search[0]-=32 ;if(strcmp(word,search)==0) num++;}