gpt4 book ai didi

c - 文件中最常见的字母(C 编程)

转载 作者:太空宇宙 更新时间:2023-11-04 07:08:25 25 4
gpt4 key购买 nike

我需要使用 C 创建一个函数来查找文件中最常见的字母。无法弄清楚我的问题,出于某种原因它总是返回 [

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

char commonestLetter(char* filename);

void main()
{
char str[101], ch;
FILE *fout;
fout = fopen("text.txt", "w");
if (fout == NULL)
{
printf("Can't open file\nIt's probably your fault, worked perfectly on my PC ;)\n");
fclose(fout);
}
printf("Enter string (to be written on file)\n");
gets(str);
fputs(str, fout);
ch = commonestLetter("text.txt");
printf("The most common letter is %c\n", ch);
fclose(fout);
}

char commonestLetter(char* filename)
{
char ch;
int i, count[26];
int max = 0, location;
FILE *f = fopen(filename, "r");
if (f == NULL)
{
printf("file is not open\n");
return;
}
for (i = 0; i < 26; i++)
count[i] = 0;

while ((ch = fgetc(f)) != EOF)
{
if (isalpha(ch))
count[toupper(ch) - 'A']++;
}

for (i = 0; i < 26; i++)
{
if (count[i] >= max)
{
max = count[i];
location = i + 1;
}
}
return location + 'A';
}

最佳答案

location=i;

不需要i+1

正如你在做的那样 location+'A';

假设 count[25] 位置的计数最高,则位置变为 25+1=26

现在 return 将是 26+65=91 这是 '['

你的代码略有修改,但保留了你的逻辑

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

char commonestLetter(char* filename);

int main()
{
char str[101], ch;
FILE *fout;
fout = fopen("text.txt", "w");
if (fout == NULL)
{
printf("Can't open file\nIt's probably your fault, worked perfectly on my PC ;)\n");
return 0;
}
printf("Enter string (to be written on file): ");
fgets(str,sizeof(str),stdin);
fputs(str, fout);
fclose(fout);
ch = commonestLetter("text.txt");
printf("The most common letter is %c\n", ch);
return 0;
}

char commonestLetter(char* filename)
{
char ch;
int i, count[26];
int max = 0, location;
FILE *f = fopen(filename, "r");
if (f == NULL)
{
printf("file is not open\n");
return;
}

memset(&count,0,sizeof(count));
while ((ch = fgetc(f)) != EOF)
{
if (isalpha(ch))
count[toupper(ch) - 'A']++;
}

for (i = 0; i < 26; i++)
{
if (count[i] >= max)
{
max = count[i];
location = i;
}
}
fclose(f);
return location + 'A';
}

输入和输出:

Enter string (to be written on file): Gil this is a testing
The most common letter is I

关于c - 文件中最常见的字母(C 编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30331602/

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