编写一个程序来计算一个字符在文件中出现的次数。 (不区分大小写... 'a' 和 'A' 被认为是相同的)

Write a program to count the number of times a character appears in the File. (Case insensitive... 'a' and 'A' are considered to be the same)

我必须编写一个程序来计算一个字符在文件中出现的次数。 (不区分大小写...'a'和'A'被认为是一样的)

     #include<stdio.h>

     #include<stdlib.h>

     #include<ctype.h>

    int main()

   {

    FILE *fp1;

   char ch,f[100],c,d;

   int ct=0;

   printf("Enter the file name\n");

   scanf("%s",f);   

   fp1=fopen(f,"r");

  printf("Enter character:");

  scanf(" %c",&c);

  do 

  { 

    printf("%c",ch);

    ch=fgetc(fp1);

    d=toupper(ch);

    printf("%c",d);

    if(c==d)

    ++ct;

    }while(ch!=EOF);

   fclose(fp1);

  printf("\n");

  printf("%d",ct);

  return 0;

  }`

这是我编写的程序,但我得到的输出是..

[ a.txt contains the string- aaa ]

现在当 运行 程序时,这是我得到的输出:

Enter the file name

a.txt

Enter character:a

aAaAa

0

我哪里做错了??

如果你输入'a',你把所有的字符都转换成Upper()...肯定不行;:=)

你需要的是检查要搜索的字符是否等于文件中的字符或其大写版本,如果是,则递增ct .

简单改变

if(c==d)

if(c==d || c==ch)

其他问题:ch这里没有初始化

printf("%c",ch);

do...while 循环的第一次迭代中。通过将上面的 printf 移到

之后来修复它
ch=fgetc(fp1);

此外,在打印之前添加检查以查看 ch 是否不是 EOF

我猜这段代码有效。

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

void main()
{

    FILE *fp1;
    char c;
    char ai,s;
    char fname[20];
    int count=0;

    clrscr();
    printf("enter the character to be counted:");
    scanf("%c",&ai);
    s=toupper(ai);
    printf("enter the file name :");
    scanf("%s",&fname);
    fp1=fopen(fname,"r");

    if(fp1==NULL)
    {
        printf("cannot open this file");
    }

    do
    {
        c=fgetc(fp1);
        if(c==ai || c==s)
        {
            count=count+1;
        }
    }

    while(c != EOF);
    printf("\nFILE '%s' has %d instances of letter %c",fname,count,ai);
    getch();
}