我需要创建一个函数,用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/

10-11 16:35