我必须编写一个程序来计算字符在文件中出现的次数。 (不区分大小写......' a' 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包含字符串 - aaa]
现在运行程序时,这是我得到的输出:
输入文件名
A.TXT
输入字符:a
AAAAA
0
我在这里做错了什么?
答案 0 :(得分:0)
如果您输入&#39; a&#39;,并将所有字符转换为上限()...它肯定无法正常工作;:=)
答案 1 :(得分:0)
您需要检查要搜索的字符是否等于文件或其大写版本中的字符,如果是,则增加ct
。
只需更改
if(c==d)
到
if(c==d || c==ch)
其他问题:ch
未在此处初始化
printf("%c",ch);
在do...while
循环的第一次迭代中。通过在
printf
来修复它
ch=fgetc(fp1);
另外,在打印之前添加一项检查以查看ch
是否不是EOF
。
答案 2 :(得分:-1)
这个代码可以解决。
#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();
}