简体   繁体   中英

Finding the most frequent character of an input text file

I am trying to read an input txt file from command line and find the most frequent character in that file for a school project. I can open the txt file and print it without an issue with the following code. Also the funcion below freqcount(), works perfectly when I give it a string from the command line. But I can't seem to make them work together. I think I'm messing up something while setting up the dest array down below. Any help would be appreciated.

Also, for non static sized strings, which one is generally better to use, malloc or calloc ?

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

#define DEST_SIZE 26 // An arbitrary size but longest string to work is 24

char freqcount(char * str){

    // Construct character count array from the input 
    // string. 
    int len = strlen(str); 
    int max = 0;  // Initialize max count 
    char result;   // Initialize result 
    int count[255] = {0};

    // Traversing through the string and maintaining 
    // the count of each character 
    for (int i = 0; i < len; i++) { 
        count[str[i]]++; 
        if (max < count[str[i]]) { 
            max = count[str[i]]; 
            result = str[i]; 
        } 
    } 

    return result; 
}

//////////////////////////////////////////////////////////////////////

int main(int argc,char ** argv){
    int i=0;
    char dest[DEST_SIZE] = {0};

    if(argc !=2){
        perror("Error: ");
        return -1;
    }

    FILE * f = fopen(argv[1], "r");
    if (f == NULL) {
        return -1;
    }
    int c;

    while ( (c=fgetc(f)) != EOF && i++<DEST_SIZE ) {
        printf("%c",c);
        dest[i]=c;
        char cnt=freqcount(dest);
        printf("%c",cnt);
    }

    return EXIT_SUCCESS;
}

Sorry I forgot to add, originally call was after the loop such as; (omitted the first part)

while ( (c=fgetc(f)) != EOF && i++<DEST_SIZE ) {
        printf("%c",c);
        dest[i]=c;
    }
    /*int l;
    for (l=0; l<DEST_SIZE;l++){
        if (dest[i] != 0){
           printf("%c\n",dest[l]); // burda da arrayi okuyor ama array 255 long oldugu icin cogu bos
     }
    }*/
    char cnt=freqcount(dest);
    printf("%s",cnt);




    return EXIT_SUCCESS;
}

when it is like this, the code returns the following with the input "An example Of the input.

An example
Of the input.(null)

Move the call of freqcount to after the while loop:

while ( (c=fgetc(f)) != EOF && i++<DEST_SIZE ) {
    printf("%c",c);
    dest[i]=c;
}
dest[i]='\0';    // terminate
char cnt=freqcount(dest);
printf("%c",cnt);

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