A state machine would look something like this :
Code:
#define STATE_LOOKING_FOR_I 1
#define STATE_FOUND_I 2
int state = STATE_LOOKING_FOR_I;
while ((ch = getchar()) != '#')
{
switch(state)
{
case STATE_LOOKING_FOR_I:
/* Move to FOUND_I state if input is an i */
if (ch == 'i')
state = STATE_FOUND_I;
break;
case STATE_FOUND_I:
if (ch == 's')
count += 1;
state = STATE_LOOKING_FOR_I;
break;
default:
printf("Error : bad state\n");
exit(0);
}
}
Total overkill for this small of a problem, but imagine you're looking for a longer string. Each character found in the correct order would lead to the next state in the sequence until you get to the final one where you add 1 to the count. At any point along the way if you see the wrong character you just go back to the first state and start over. No need to mess with multiple flags for each character and lots of nested if statements, just a simple check in each intermediate state.
You could make it work with arbitrary strings; something like (untested code but you get the idea):
Code:
const char sequence[] = "looking";
int state = 0;
while ((ch = getchar()) != '#')
{
if (ch == sequence[state]) /* found next character in sequence */
{
if (state == (strlen(sequence) - 1)) /* matched all the way to end of sequence */
{
count += 1;
state = 0;
}
else
state += 1; /* check next char in sequence */
}
else
state = 0; /* start over from beginning of sequence */
}