Reputation: 25
#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);
c=toupper(c);
do
{
ch=fgetc(fp1);
d=toupper(ch);
if(c==d||c==ch)
++ct;
} while(ch!=EOF);
fclose(fp1);
printf("\n");
printf("%d",ct);
return 0;
}
here my file contains aAaAaA
and when I execute this code, I am getting 6 characters in the file but I should get it as 3 characters because a and A are case insensitive. What's wrong with this code?
Upvotes: 0
Views: 3877
Reputation: 134356
In your code, essentially, you're incrementing the counter unconditionally.
if(c==d || c==ch)
^ ^
| |
UPPERCASE original
will increment the counter for both the cases.
As the code is currently written . for an input of a
or A
, c
is always A
, so
a
is read from file, d
is A
, so, c==d
gives TRUE, increments the counterA
is read from file, ch
is A
, so as d
thereby c==d
gives TRUE, increments the counter.What you actually want is to consider the input as case-sensitive [A
and a
should be counted as differnt characters.]
Also, as Mr. @coolguy mentioned in his comments, check the return value of fopen()
for success before using the returned pointer.
Solution:
toupper()
. Use the actual input instead..
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main(void)
{
FILE *fp1 = NULL;
char ch,f[100],c,d;
int ct=0;
printf("Enter the file name\n");
scanf("%s",f);
fp1=fopen(f,"r");
if (!fp)
{
printf("Cannot open file for reading\n");
exit(-1);
}
printf("Enter character:");
scanf(" %c",&c);
do
{
ch=fgetc(fp1);
if(ch == c)
++ct;
}while(ch!=EOF);
fclose(fp1);
printf("%d\n",ct);
return 0;
}
Upvotes: 3