Friday, January 9, 2015

String Scanner in C

 SCANNER   (Step1 in Compiler Designing Approach)
      =======

      Based on Deterministic Finite Automation (DFA) for a REAL number
      with optional Integer and Fractional Part.

   -> find for the given string entered is whether
       i>   Identifier
       ii>  Integer number
       iii> Real number
       it check all posibility and determine the validity of entered string.


DFA for Real number
-> L = Letter
-> D = Digit
-> . = Decimal Point
       ===================================================
       ||        ||        NEXT SYMBOL                  ||
       || STATE  =========================================
       ||        ||   L     ||     D     ||     .       ||
       ||===============================================||
       || START  ||  ID     ||   INT     ||    S1       ||
       || ID     ||  ID     ||   ID      ||  INVALID    ||
       || INT    || INVALID ||   INT     ||   REAL      ||
       || REAL   || INVALID ||  REAL     ||  INVALID    ||
       || S1     || INVALID ||  REAL     ||  INVALID    ||
       ===================================================
*/


#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#include <process.h>

void main()
{
char inputstr[50];
char nextSymbol,state[10]="START";
int i;
clrscr();

cout<<"\n*****Scanner (Lexical Analysis) *****\n";
cout<<"Enter String : ";
cin.getline(inputstr,50,'\n');

for(i=0;inputstr[i]!=NULL;i++)
{
nextSymbol = inputstr[i];

if(strcmp(state,"INVALID")==0)
break;

//initially state of inputstr is in start.
if(strcmp(state,"START")==0){
if(isdigit(nextSymbol))
strcpy(state,"INT");
else if(isalpha(nextSymbol))
strcpy(state,"ID");
else if(nextSymbol=='.')
strcpy(state,"S1");
else
strcpy(state,"INVALID");
}
else if(strcmp(state,"ID")==0){
if(isdigit(nextSymbol))
strcpy(state,"ID");
else if(isalpha(nextSymbol))
strcpy(state,"ID");
else
strcpy(state,"INVALID");
}
else if(strcmp(state,"INT")==0){
if(isdigit(nextSymbol))
strcpy(state,"INT");
else if(nextSymbol=='.')
strcpy(state,"REAL");
else
strcpy(state,"INVALID");
}
else if(strcmp(state,"REAL")==0){
if(isdigit(nextSymbol))
strcpy(state,"REAL");
else
strcpy(state,"INVALID");
}
else if(strcmp(state,"S1")==0){
if(isdigit(nextSymbol))
strcpy(state,"REAL");
else
strcpy(state,"INVALID");
}
}

if(strcmp(state,"S1")==0 || strcmp(state,"INVALID")==0)
cout<<"\n\nINVALID INPUT";
else
cout<<"\n\nString State is : "<<state;

end:
getch();
}



for more codes you can Visit http://codesofprogramming.blogspot.in/

No comments:

Post a Comment