c - 用 C 计算文件中的字母
问题描述
我正在尝试创建一个程序,该程序从文件中读取并计算文件中每个字母字符的出现次数。以下是我到目前为止的内容,但是返回的计数(存储在 counters 数组中)比预期的要高。
void count_letters(const char *filename, int counters[26]) {
FILE* in_file = fopen(filename, "r");
const char ALPHABET[] = "abcdefghijklmnopqrstuvwxyz";
if(in_file == NULL){
printf("Error(count_letters): Could not open file %s\n",filename);
return;
}
char line[200];
while(fgets(line, sizeof(line),in_file) != NULL){ //keep reading lines until there's nothing left to read
for(int pos = 0; pos < sizeof(line); pos++){//iterate through each character in line...
if(isalpha(line[pos])){//skip checking and increment position if current char is not alphabetical
for(int i = 0; i < 26; i++){//...for each character in the alphabet
if(tolower(line[pos]) == tolower(ALPHABET[i]))//upper case and lower case are counted as same
counters[i]++; // increment the current element in counters for each match in the line
}
}
}
}
fclose(in_file);
return;
}
解决方案
我的两分钱用于一个更简单的解决方案(你有很多循环;))。在大多数情况下,首选逐行读取输入,但由于您只是在这里计算字符,我认为这不是其中之一,最终会增加复杂性。该答案还假定ASCII 字符编码,正如另一个答案的评论中所述,C 标准不保证这一点。您可以根据需要进行修改以char ALPHABET
获得最终的便携性
#include <stdio.h>
#include <ctype.h>
#define NUM_LETTERS 26
int main(void)
{
FILE* in_file = fopen("/path/to/my/file.txt", "r");
if (in_file == NULL) exit(-1);
unsigned charCounts[NUM_LETTERS] = {0};
int curChar;
// rather than reading line-by-line, read one character at a time
while ((curChar = fgetc(in_file)) != EOF)
{
// only proceed if it is a letter
if (isalpha(curChar))
{
// this is bad if not using ASCII, instead you'd need another
// loop to check your ALPHABET, but increment the count here
(charCounts[tolower(curChar) - 'a'])++;
}
}
// print out the results
for (int i=0; i<NUM_LETTERS; i++)
{
// 'A'+i also assumes ASCII encoding
printf("%c: %u\n", 'A'+i, charCounts[i]);
}
}
演示使用stdin
而不是文件。
推荐阅读
- java - 集成测试包含什么以及如何设置它们
- tomcat - Tomcat 8 - 语句缓存设置
- apache-kafka - 测试 kafka 是否准备好,可以从 cli 访问主题
- opencv - 为什么我的 cv::Mat-Matrix 稀疏而不密集?
- python - 为什么 python 在我的 Surface Book 2 上运行这么慢
- three.js - How can I move only specific vertices from my vertexshader ? (And how to choose them)
- javascript - 如何使用反应钩子对组件进行单元测试?
- c# - 循环访问 Windows 窗体控件并将名称导出到列表
- crystal-reports - 使用 if 语句不断收到基本语法错误
- sql - 使用 BULK INSERT 插入空格而不是 NULL