簡體   English   中英

查找輸入文本文件中出現頻率最高的字符

[英]Finding the most frequent character of an input text file

我正在嘗試從命令行讀取一個輸入 txt 文件,並在該文件中為學校項目找到最常見的字符。 我可以使用以下代碼打開 txt 文件並打印它而不會出現問題。 當我從命令行給它一個字符串時,freqcount() 下面的函數也能完美地工作。 但我似乎無法讓他們一起工作。 我想我在下面設置 dest 數組時弄亂了一些東西。 任何幫助,將不勝感激。

此外,對於非 static 大小的字符串,通常使用哪個更好, malloc還是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;
}

對不起,我忘了補充,原來調用是在循環之后,例如; (省略第一部分)

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

當它是這樣時,代碼返回以下輸入“輸入的示例。

An example
Of the input.(null)

freqcount的調用移到 while 循環之后:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM