c - 在文件中查找不同字符的实例

标签 c

在这个程序中,我想打印出文件中不同字符的实例。输出将包含三个变量:出现次数、字母的十六进制以及字母本身。有人可以帮我弄这个吗?我被困住了!

 Results of program should be something like this:
 10 instance  of character 0x4s (O)
 10 instance  of character 0x51 (W)
 10 instance  of character 0x51 (Y)
 2 instances of character 0x65 (a)
 18 instances of character 0x67 (c)
 16 instances of character 0x81 (d)


//here is my program. 
#include <stdio.h>
#include <stdlib.h> 
#include <string.h>

const char FILE_NAME[] = "input.txt";


int main(argc, *argv[]) {

    char temp;   
     char count[255];

FILE *in_file;   
int ch;

fp = fopen(FILE_NAME, "r");
if (in_file == NULL) {
    printf("Can not open %s \n", FILE_NAME);
    exit(0);
}

while (!feof(fp)) {

    ch = fgetc(fp);

if(strchr(count, ch)!= NULL)
{

}

}
printf("%d instance of character (%c)", count);


fclose(in_file);
return (0);
}

最佳答案

这就是您想要的(基于您的代码,以及我的许多评论):

#include <stdio.h>
#include <stdlib.h> 
#include <string.h>
#include <ctype.h>  // you need this to use isupper() and islower()

const char FILE_NAME[] = "input.txt";

int main(int argc,char *argv[]) {
    char temp;   
    unsigned count[52] = {0};  // An array to store 52 kinds of chars
    FILE *fp;   
    int i;

    fp = fopen(FILE_NAME, "r");
    if (fp == NULL) {
        printf("Can not open %s \n", FILE_NAME);
        exit(0);
    }

    while((temp = fgetc(fp)) != EOF) {   // use this to detect eof
        if(isupper(temp))
            count[26+(temp-'A')]++;   // capital letters count stored in 26-51
        if(islower(temp))
            count[temp-'a']++;        // lower letters count stored in 0-25
    }
    fclose(fp);  // When you don't need it anymore, close it immediately.

    for(i = 0; i < 26; i++)
        if(count[i])
            printf("%d instance of character 0x%x (%c)\n", count[i], 'a'+i, 'a'+i);
    for(; i < 52; i++)
        if(count[i])
            printf("%d instance of character 0x%x (%c)\n", count[i], 'A'+i-26, 'A'+i-26);
    return (0);
}

关于c - 在文件中查找不同字符的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12950883/

相关文章:

c - 递归哈希代码?

c - 程序在NetBeans中运行时无法输入数据

c - 优雅地杀死 C 的 pthread 中的阻塞线程?

c - 64位计算机中INT的最大值

c - C 中的段错误

c - 在单独的头文件中定义的结构

c - 搜索文件并返回值 - 超快

c - 指针和字符串之间的警告比较

c - 套接字无法在基本客户端/服务器之间连接

c - Mac .dylib 链接找不到 header