gpt4 book ai didi

c - 检查文件中最常见的字母时如何忽略 ctrl+z(不区分大小写)

转载 作者:行者123 更新时间:2023-11-30 16:41:35 25 4
gpt4 key购买 nike

该函数需要查找文件中最常见的字符,并从用户那里获取数据。我使用 ctrl+z 来终止。

问题是当我输入大字符时,例如:A + ctrl+Z,那么它会将Z视为最常见的字符。(如果字符数量相同,则按字母顺序返回最大的。空文件将返回'\0')。

char commonestLetter(){
char ch;
int count[26] = {0}, max = 0, index, i;
FILE* f = fopen("input.txt","w");
if (f == NULL){
printf("Failed to open the file \n");
return;
}
printf("Please enter the characters one by one, followed by enter\n");
printf("Ctrl + z and enter to finish\n");
while((ch = getchar()) != EOF){
fprintf(f,"%c",ch);
_flushall();
if (isalpha(ch))
count[ch - 'a']++;
}
fseek(f, 0, SEEK_END);
if (ftell(f) == 0){
ch = '\0';
return ch;
}
for (i = 0; i < 26; i++){
if (count[i] >= max){
max = count[i];
index = i;
}
}
fclose(f);
return index + 'A';
}

int main(){
char ch;
ch = commonestLetter();
if(ch)
printf("The commonest letter is %c", ch);
else
printf("No letters in the file");
printf("\n");
system("pause");
return 0;
}

最佳答案

  1. 您声明该函数应该在文件中查找最常见的字母,但您从标准输入中读取字母。
  2. 要获得最常见的字母忽略大小写,您必须使用字母提升函数,例如 tolower()。

试试这个:

#include <stdio.h>
#include <ctype.h>

char commonestLetter(char *file_name)
{
char ch, max_char = '\0';
int count[26] = {0}, max_count = 0;

FILE *f = fopen(file_name, "r");
if (f == NULL) {
printf("Failed to open the file %s\n", file_name);
return '\0';
}

while (fread(&ch, 1, 1, f) > 0) {
if (isalpha(ch) &&
(++count[tolower(ch) - 'a']) > max_count)
max_char = ch;
}
fclose(f);
return max_char;
}

int main(int argv, char *argc[])
{
char ch;
if (argv < 2) {
printf("Usage: %s filename\n", argc[0]);
exit();
}

ch = commonestLetter(argc[1]);
if(ch)
printf("The commonest letter in the file %s is '%c'\n",
argc[1], ch);
else
printf("No letters in the file %s\n", argc[1]);

return 0;
}

关于c - 检查文件中最常见的字母时如何忽略 ctrl+z(不区分大小写),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46238203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com