Sunday, 6 July 2014

Lexical Analyzer

Simple Lexical Analyzer program. It takes the filename in the same directory as the input and analyzes the program for variables operators and special characters. and prints the output for each values separately.

 #include<stdio.h>  
 #include<conio.h>  
 #include<string.h>  
 void main()  
 {  
      FILE *fp;  
      int i=0;  
      char input[100],filename[20];  
      clrscr();  
      printf("Enter Filename : ");  
      scanf("%s",filename);  
      fp=fopen(filename,"r");  
      while(!feof(fp))  
      {  
           input[i]=fgetc(fp);  
           i++;  
      }  
      input[--i]='\0';  
      for(i=0;i<strlen(input);i++)  
      {  
           if(isalpha(input[i]))  
           {  
                printf("%c is a Character.\n",input[i]);  
           }  
           else if(input[i]=='='||input[i]=='+'||input[i]=='-'||input[i]=='*'||input[i]=='/'||input[i]=='%')  
           {  
                printf("%c is an Operator.\n",input[i]);  
           }  
           else if(isspace(input[i])||iscntrl(input[i]))  
           {  
           }  
           else if(isdigit(input[i]))  
           {  
                printf("%c is a number.\n",input[i]);  
           }  
           else  
           {  
                printf("%c is a Special character.\n",input[i]);  
           }  
      }  
      getch();  
 }  
Notify the Suggestions about the program through comments ... :)

8 comments:

  1. why no & in scan statement ?

    ReplyDelete
  2. seems like the ads have gone now ...how did u remover da GRK?

    ReplyDelete
    Replies
    1. just removed the HTML/javascript plugin in the page.. :)

      Delete
  3. what is the use of iscntrl() fn?

    ReplyDelete
    Replies
    1. The file may contain carriage return, or backspace characters in it.
      iscntrl() is used to detect those characters and i used it to ignore those characters using if statement.

      Delete