用c++ 统计英文文本文件中单词的个数并统计某一个特定单词出现的频度,来串代码
时间: 2023-06-03 08:04:40 浏览: 52
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_LEN 100
void countWords(FILE *file, char *specificWord);
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <file_name> <word>\n", argv[0]);
exit(EXIT_FAILURE);
}
FILE *file = fopen(argv[1], "r");
if (file == NULL) {
printf("Failed to open file: %s\n", argv[1]);
exit(EXIT_FAILURE);
}
countWords(file, argv[2]);
fclose(file);
return 0;
}
void countWords(FILE *file, char *specificWord) {
int wordCount = 0;
char word[MAX_WORD_LEN];
while (fscanf(file, "%s", word) == 1) {
if (strcmp(word, specificWord) == 0) {
wordCount++;
}
}
printf("Total words: %d\n", wordCount);
}