文件上最常见的字母(C编程)

时间:2015-05-19 16:51:26

标签: c

我需要创建一个函数,使用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';
}

2 个答案:

答案 0 :(得分:2)

待办事项

location=i;

无需i+1

正如您所做的那样location+'A';

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

现在return26+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';
}

输入&amp;输出:

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

答案 1 :(得分:1)

这里的问题是,在你的代码中,

location = i + 1;

location最后是i+1,您返回location + 'A';,这是(因为您的输入,可能)(25+1) + 'A',即{{} 1}}这是26 + 'A'