急問--c++!!(10分)

2008-01-08 5:48 am
用c點寫:一個英文字或詞係文章中出現次數!

回答 (1)

2008-01-08 7:31 pm
✔ 最佳答案
Here is a C++ source program which will count the number of occurrences of a given word in a given file.
The usage is
occur file-name word
The link to a text file of the source is:
http://mathmate.brinkster.net/
and the program source is:

/* occur.cpp - displays the number of times a word or phrase appears in a text.
NOTE: The word to be counted is case sensitive.
If case insensitivity is required, use toupper() to convert
all words to upper case before comparison.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
if(argc<3)
{
printf("Usage: occur fileName wordOrPhrase\n");
printf("Example: occur textfile good\n");
exit(0);
}
FILE *f1=fopen(argv[1],"r");
if(f1==NULL)
{
printf("File %s does not exist. Please try again\n");
exit(0);
}
char li[200]; // max. line length of 200 characters
int count=0;
while((fgets(li,199,f1))!=NULL)
{
char *p=strtok(li," ,.!?;");
do
{
// p is the token delimited by any of space,.!? or ;
// argv[2] is the string to be counted
if(strcmp(p,argv[2])==0)count++;
}while((p=strtok(NULL," ,.!?;"))!=NULL);
}
printf("%s occurred %d times in the given text\n",argv[2],count);
return 0;
}


收錄日期: 2021-04-13 14:54:18
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20080107000051KK04058

檢視 Wayback Machine 備份