-1

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 ':' ?

Raj Chauhan
  • 15
  • 1
  • 8

1 Answers1

0

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.

J...S
  • 5,079
  • 1
  • 20
  • 35
  • 1
    while((c=fgetc(fp))!=EOF) -- this worked! Thnx. a little yet powerful concept of operator precedence. – Raj Chauhan Jul 14 '18 at 13:58
  • @RajChauhan No it doesn't work. It fails (terminates prematurely before the end-of-file) when there's a character with code 255 in the input which gets sign-extended to -1, the value of the EOF macro. – Jens Jul 14 '18 at 14:05
  • @RajChauhan You must use `int c;` instead of `char c;` since an int can fit all char values plus another for EOF. – Jens Jul 14 '18 at 14:11