Wednesday, July 13, 2016

Program to Check Given Input String is Valid Identifier or Not

#include"stdio.h"
#include"conio.h"
#include"string.h"

void main(){
    char str[20],key[][32]= {"auto","double","int","struct",
    "break","else","long","switch","case","enum","register",
    "typedef","char","extern","return","union","const","float",
    "short","unsigned","continue","for","signed","void","default",
    "goto","sizeof","volatile","do","if","static","while" } ;
    int i,j=0,flag;
    clrscr();
  while(j<=6){
    flag=0;
    printf("\nEnter string : ");
    gets(str);
    for(i=0;i<=31;i++){
    if(flag==strcmpi(str,key[i]))
        flag = 1;
    }
    if(flag==0){
     for(i=0;i<strlen(str);i++){
      if(str[i]=='_' || isalpha(str[i]) || isdigit(str[i]) && !isspace(str[i]) && !isdigit(str[0]))
        flag = 0;
      else{
       flag = 1;
       break;
      }
     }
    }
    if(flag==0)
    printf("Valid Identifier\n");
    else
    printf("Invalid Identifier\n");
  j++;
  }
    getch();
}
---------------------------------------------------------------------------------------------------
In this Program one array is defined to store keyword to check input is keyword or not using 'strcmpi()' function. In other loop it checks for '_'(checks all 'str[i]') , alphabets(using 'isalpha()') and whitespace (using 'issapce()') constrains and if alphabet(not) or space(detected) then it means input might be containt ant numeric value or special symbol which will go to else part and break out of loop for preventing resetting  flag variable.