繁体   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