I am trying to create a simple finite state machine in C and I'm quite confused on how to get started. I tried looking online but nothing has really cleared this up for me.
My goal is to check if a string is octal, hex or a decimal.
To be octal the string must start with a 0, followed by digits 0-7. To be hex the string must start with 0x or OX, followed by (a-f, A-F, 0-9)
My attempt at creating the states would be:
typedef enum {
ERROR,
OCTAL,
HEX,
DECIMAL
} stringStates;
Now, I would then use a switch statement to go through the entirety of the string and switch between the different states until I have correctly identified which state it belongs to.
while (current_Position<=end_String-1)
{
switch( "input something here")
{
case 0:
//process string
break;
case 1:
//process string
break;
case 2:
//process string
break;
case 3:
//process string
break;
default:
break;
}
}
This concept is still very new to me and I'm having hard time understanding its implementation. If anyone can shed some light, it'll be much appreciated.
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.