用于计算字符在文件中出现的次数的程序(不区分大小写)

时间:2015-09-12 07:38:58

标签: c

在在线编辑器中执行此代码。但始终获取File 'test.txt' has 0 instances of letter 'r'。该怎么做?File 'test.txt' has 99 instances of letter'r'。这是预期的输出。

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
    FILE *fptr;
    int d=0;
    char c;
    char ch,ck;
    char b[100];
    printf("Enter the file name\n");
    scanf("%19s",b);
    fptr=fopen(b,"r");
    printf("Enter the character to be counted\n");
    scanf(" %c",&c);
    c=toupper(c);
    if(fptr==NULL)
    {
        exit(-1);
    }
    while((ck=fgetc(fptr))!=EOF)
    {
        ch=toupper(ck);
        if(c==ch||c==ck)
            ++d;
    }
    fclose(fptr);
    printf("File '%s' has %d instances of letter '%c'.",b,d,c);
    return(0);
}

2 个答案:

答案 0 :(得分:0)

我测试了它。它工作正常。在没有提供失败的测试文件的情况下,我无法检测到您的问题。就我而言,它做了它应该做的事情 - 它计算指定字符在指定文件中出现的次数(不区分大小写)。这是你的代码的美化版本。

#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* strlen */
#include <ctype.h>

#define MAX_FILENAME_LENGTH 100

int main(int argc, char **argv) {
    /* Variables */
    FILE *file = NULL;
    int count = 0, file_char;
    char target_char, filename[MAX_FILENAME_LENGTH];
    /* Getting filename */
    printf("Enter the file name: ");
    fgets(filename, MAX_FILENAME_LENGTH, stdin);
    /* Removing newline at the end of input */
    size_t filename_len = strlen(filename);
    if(filename_len > 0 && filename[filename_len - 1] == '\n') {
        filename[filename_len - 1] = '\0'; }
    /* Opening file */
    file = fopen(filename, "r");
    if(file == NULL) exit(EXIT_FAILURE);
    /* Getting character to count */
    printf("Enter the character to be counted: ");
    scanf(" %c", &target_char);
    target_char = toupper(target_char);
    /* Counting characters */
    while((file_char = fgetc(file)) != EOF) {
        file_char = toupper(file_char);
        if(target_char == file_char) ++count; }
    /* Reporting finds */
    printf("File '%s' has %d instances of letter '%c'.",
           filename, count, target_char);
    /* Exiting */
    fclose(file);
    return EXIT_SUCCESS; }

答案 1 :(得分:0)

的问题:

  1. ck应该是int,而不是char @alk has pointed out,因为fgetc会返回int,而不是char
  2. 根据标题,您需要不区分大小写的比较。您的代码不会这样做。解决方案就是:

    if(c==ch||c==ck)
    

    需要

    if(c == ch || (tolower(c)) == ck) /* Compare upper with upper, lower with lower */