[英]Most common letter on a file (C programming)
I need to create a function that finds the most common letter in a file using C. Can't figure out my problem, for some reason it always returns [
. 我需要创建一个函数来使用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';
}
Do 做
location=i;
No need of i+1
不需要i+1
As you are doing location+'A';
当您在做location+'A';
Suppose the location count[25]
has the highest count, so the location becomes 25+1=26
. 假设位置count[25]
的计数最高,则位置变为25+1=26
。
Now the return
will be 26+65=91
which is of '['
现在return
26+65=91
,即'['
The code of yours is slightly modified but the logic of your is kept 您的代码略有修改,但您的逻辑得以保留
#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';
}
Input & Output: 输入输出:
Enter string (to be written on file): Gil this is a testing
The most common letter is I
The problem here is, in your code, 这里的问题是,在您的代码中,
location = i + 1;
location
is i+1
at the end, and you're returning location + 'A';
location
是结尾处的i+1
,您将返回location + 'A';
which is (because of your input, probably) (25+1) + 'A'
, ie, 26 + 'A'
which is [
. 这是(由于您的输入,可能是) (25+1) + 'A'
,即26 + 'A'
这是[
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.