Finite State Machine In C

心已入冬 提交于 2019-12-04 21:36:33

It is a pretty much straight forward question and the solution is also very simple.

I have 7 states namely from 0 to 6 as shown by diagram.0 is the initial state. 3,4,5 could be the final states and 6 is the dead state.

state 0: Initial state and from this state we can only encounter following chars:

0 or O or 1-9

if any other char then an error is there and no need to process further.

state 1: if char from state 0 is 0 then this is the next state and

if char from this state is x then the string is hexadecimal(state=4) and no need to process further as any char can follow.

if char from this state is 0-7 then string is octal(state=5) and we process till the end of string to see if we get any char different from 0-7, if we do then error is there as invalid string and no need to process further as soon as we get it.

state 2: if char from state 0 is O then this is the next state and from this state if next char is X then string is hexadecimal(state=4) and no need to process further, if it is not then error is there.

state 3: if char from state 0 is 1-9 then string is decimal number(state=3) and we process till the end of string to see if we get any char different from 0-9, if we do then error is there as invalid string and no need to process further as soon as we get it.

state 4:hexadecimal number

state 5:octal number

state 6:error meaning invalid string

Here is the C code. I have taken the length of the string to be 9, just for simplicity and nothing else.

#include <stdio.h>
#include <stdlib.h>
int main()
{
  char *a="066676777";
  int state=0;int i=0;
  while(state!=6&&i<9)
  {
      switch(state)
      {
      case 0:
        if(a[i]=='0')
            state=1;
        else if(a[i]=='O')
            state=2;
        else if(a[i]>=49&&a[i]<=57)
            state=3;
        else {state=6;i=9;}
        break;
      case 1:
         if(a[i]=='x')
         {
              state=4;i=9;
         }
         else if(a[i]>=48&&a[i]<=55)
         {
             state=5;
             while(i<9)
                if(a[i]>=48&&a[i]<=55)
                 ++i;
                else {state=6;i=9;}
         }
         else {state=6;i=9;}
         break;
      case 2:
          if(a[i]=='X')
          {
              state=4;i=9;
          }
          else {state=6;i=9;}
         break;
      case 3:
          while(i<9)
            if(a[i]>=48&&a[i]<=57)
                ++i;
            else {state=6;i=9;}
            break;
      default:
        printf("please select correct initial state");
         break;
      }
      ++i;
    }
    if(state==3)
      printf("it is a decimal number");
    else if(state==4)
      printf("it is a hexadecimal number");
    else if(state==5)
      printf("it is a octal number");
    else printf("error encountered as invalid string");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!