I am unable to find out if the ternary operator is present or not through following code.. Plz help.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void one();
int main()
{
FILE *fp;
fp=fopen("C:/Users/HP/Documents/NetBeansProjects/CD2/1.txt","r");
char c;
void one()
{
char c;
while((c=fgetc(fp)!=EOF))
{
if(c==':')
{
printf("\nThe ternary operator present");
return;
}
}
}
while((c=fgetc(fp))!=EOF)
{
printf("\n-->%c",c);
if(c=='?')
{
one();
}
}
return 0;
}
I want to know why this code doesn't work and say if the ternary operator is present or not in file 1.txt
The output shows all characters till '?' if we print them, but why it's not finding for a colon ':' ?
The exit condition of the while
loop may be the problem. =
has lesser precedence than !=
operator. So
(c=fgetc(fp)!=EOF)
gets evaluated like
(c= (fgetc(fp)!=EOF) )
See this for the precedence of various operators in C.
You could do
while((c=fgetc(fp))!=EOF)
instead. First assign the return value of fgetc()
to c
and then do the comparison.
ie, the variable c
gets the result of the comparison which means the value is either 0
or 1
.
Your program should be checking for the ?
and the other operands as well.
See this.
A simple check may not be enough for cases like the 'operator' being part of a string like
char str[]="the ternary operator is ?:";
Checking for the occurrence in such cases is a bit complex.
Edit:
As Jens pointed out, fgetc()
returns an int
not a char
. So make c
an int
instead of a char
.
See this post.