我正在尝试从命令行读取输入 txt 文件,并在该文件中找到学校项目中最常用的字符。我可以打开 txt 文件并打印它,而以下代码没有问题。此外,freqcount(( 下面的功能在我从命令行给它一个字符串时可以完美运行。但我似乎不能让他们一起工作。我想我在下面设置目标数组时搞砸了一些东西。任何帮助将不胜感激。
另外,对于非静态大小的字符串,哪个通常更好用,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("%cn",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]=' '; // terminate
char cnt=freqcount(dest);
printf("%c",cnt);