gpt4 book ai didi

C - 文件中的字符数

转载 作者:行者123 更新时间:2023-12-04 12:02:57 25 4
gpt4 key购买 nike

所以我想制作一个程序来计算文件中每个字符的出现次数。例如:

字符 0x67 (g) 的 4 个实例

字符 0x68 (h) 的 11 个实例

等等

我不确定如何显示和计算实例。

有什么想法吗?

#include <stdio.h>
const char FILE_NAME[] = "input.txt";
#include <stdlib.h>

int main() {

int count = 0; /* number of characters seen */
FILE *in_file; /* input file */

/* character or EOF flag from input */
int ch;

in_file = fopen(FILE_NAME, "r");
if (in_file == NULL) {
printf("Cannot open %s\n", FILE_NAME);
exit(8);
}

while (1) {
ch = fgetc(in_file);
if (ch == EOF)
break;
++count;
}
printf("Number of characters in %s is %d\n",
FILE_NAME, count);

fclose(in_file);
return (0);

最佳答案

这是我想出的...

#include<stdio.h>
#include<stdlib.h>

int main() {
/* a buffer to hold the count of characters 0,...,256; it is
* initialized to zero on every element */
int count[256] = { 0 };

/* loop counter */
int k;

/* file handle --- in this case I am parsing this source code */
FILE *fp = fopen("ccount.c", "r");

/* a holder for each character (stored as int) */
int c;

/* for as long as we can get characters... */
while((c=fgetc(fp))) {

/* break if end of file */
if(c == EOF) break;

/* otherwise add one to the count of that particular character */
count[c]+=1;
}

/* now print the results; only if the count is different from
* zero */
for(k=0; k<256; k++) {
if(count[k] > 0) {
printf("char %c: %d times\n", k, count[k]);
}
}
/* close the file */
fclose(fp);

/* that's it */
return 0;
}

我使用以下命令编译代码(OS X 10.7.4 上的 GCC 4.8.1)

gcc ccount.c -Wall -Wextra -pedantic -ansi

它编译时没有警告也没有错误;这是输出:

char 
: 40 times
char : 190 times
char ": 6 times
char #: 2 times
char %: 2 times
char ': 1 times
char (: 11 times
char ): 11 times
char *: 23 times
char +: 3 times
char ,: 5 times
char -: 3 times
char .: 9 times
char /: 20 times
char 0: 5 times
char 1: 1 times
char 2: 3 times
char 5: 3 times
char 6: 3 times
char :: 1 times
char ;: 13 times
char <: 3 times
char =: 7 times
char >: 3 times
char E: 2 times
char F: 2 times
char I: 2 times
char L: 1 times
char O: 1 times
char [: 4 times
char \: 1 times
char ]: 4 times
char a: 29 times
char b: 4 times
char c: 36 times
char d: 15 times
char e: 49 times
char f: 25 times
char g: 4 times
char h: 22 times
char i: 36 times
char k: 9 times
char l: 19 times
char m: 5 times
char n: 35 times
char o: 38 times
char p: 9 times
char r: 34 times
char s: 22 times
char t: 49 times
char u: 16 times
char v: 1 times
char w: 4 times
char y: 2 times
char z: 3 times
char {: 5 times
char }: 5 times

关于C - 文件中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19416047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com