【发布时间】:2021-12-12 00:29:16
【问题描述】:
我正在尝试创建一个程序,该程序从文件中读取并计算文件中每个字母字符的出现次数。以下是我到目前为止的内容,但是返回的计数(存储在 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;
}
【问题讨论】:
-
pos < sizeof(line)是一个错误的测试。您正在测试line(200) 中的所有字符,而不是实际读取的内容。更改为pos < strlen(line)。 -
以后在询问有关调试程序的问题时,请提供minimal reproducible example。这意味着其他人无需任何更改即可编译和运行的完整程序——包括它需要的所有
#include语句和main例程。它还包括样本输入、观察到的输出和所需的输出。 -
会做 ^ 谢谢你的建议,我是新来的 :)
-
在 void函数的末尾不需要return,它会自动完成。 -
@Dan,在这里修改您的问题标题以将其标记为“已解决”是不习惯或不合适的。由于您已经回滚了一次该编辑的回滚,因此我将标记此问题而不是再次回滚。