宏定义
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
//限定单词长度
#define MAX_WORD_LENGTH 100
函数
通过ispunct检查所传的字符是否是标点符号字符,为真则替换成结束符。
// 移除字符串末尾的标点符号
void remove_punctuation(char *word) {
int len = strlen(word);
while (len > 0 && ispunct((unsigned char)word[len - 1])) {
word[len - 1] = '\0'; // 替换为字符串结束符
len--;
}
}
%99s格式化,防止缓冲区溢出;strcmp判断所指向的字符字符串是否相等,返回0则次数自增;
int count_specific_word(const char *filename, const char *word) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("打开文件错误");
return -1;
}
char current_word[MAX_WORD_LENGTH];
int count = 0;
// 使用 %99s 确保不会超出 current_word 数组的边界
while (fscanf(file, "%99s", current_word) == 1) {
remove_punctuation(current_word); // 移除单词末尾的标点符号
if (strcmp(current_word, word) == 0) {
++count;
}
}
fclose(file);
return count;
}
主函数
检查命令行数,防止程序没有接收到足够的参数就被调用;通过函数调用打印出次数。
int main(int argc, char *argv[]) {
if (argc < 3) {
fprintf(stderr, "用法: %s <文件名> <单词>\n", argv[0]);
return -1;
}
const char *filename = argv[1];
const char *word = argv[2];
int word_count = count_specific_word(filename, word);
if (word_count >= 0) {
printf(" '%s' 单词出现%d 次在 %s.里\n", word, word_count, filename);
} else {
fprintf(stderr, "计算出错.\n");
}
return 0;
}
执行结果

文章参考与<零声教育>的C/C++linux服务期高级架构系统教程学习: https://it.0voice.com/p/t_pc/course_pc_detail/camp_pro/course_2U9D57IzMfQsoiaMuokdvXYV11c
本文介绍了如何使用C++编写一个程序,统计指定文件中特定单词的出现次数,同时处理字符串中的标点符号。程序通过宏定义、函数实现和命令行参数传递,参考了《零声教育》的Linux服务期高级架构系统教程。
2688






