简体   繁体   中英

How to ignore the ctrl+z, when checking the most common letter in a file (not case sensitive)

The function needs to find the most common character in a file and also get the data from the user. I used ctrl+z to terminate.

The problem is when I enter big character like: A + ctrl+Z , then it counts the Z as the most common one. (If there is the same amount of character, it will return the biggest alphabetically. Empty file will return '\\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. You declared that the function should find the most common letter IN A FILE, but you read letters from stdin.
  2. To get the most common letter ignoring case, you have to use letter-elevating function like tolower().

Try this:

#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;   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM