Code:
#include <stdio.h>
main()
{
int state, n=0;
char input;
state=0;
fputs("Enter a positive or negetive integer\n", stdout);
while ( (input=getchar()) !='\n' )
{
switch ( state )
{
case 0 : (input=='+'||'-')?(state=2):(state=1);
break;
case 1 : (isdigit(input))?(state=2):(state=3);
break;
case 2 : (isdigit(input))?(state=2):(state=3);
break;
case 3 : (isdigit(input) || input=='+' || input =='-')?(state=2):(state=5);
break;
case 4 : (isdigit(input))?(state=2):(state=5);
}
}
if ( state == 2 )
printf("Accepted state = A\n");
else
printf("Rejected, state = R\n");
return 0;
}
the above is supposed to accept positive or negative numbers...
example: +12132
or: 12345
or: -12345
or: 1
it is supposed to regect all else. including
1,111,111
+123+1
+
johnyboy
1johnyboy1
j12345
the program does everything it should except it accepts illegal characters as long as they arn't the last digit.
Code:
#include <stdio.h>
main()
{
int state, n=0;
char input;
state=0;
fputs("Enter a positive or negetive integer\n", stdout);
while ( (input=getchar()) !='\n' )
{
switch ( state )
{
case 0 : (input=='+'||'-')?(state=3):((isdigit(input))?(state=1):(state=2));
break;
case 1 : (isdigit(input))?(state=1):(state=2);
break;
case 2 : (state=2);
break;
case 3 : (isdigit(input))?(state=1):(state=5);
}
}
if ( state == 1 )
printf("Accepted state = A\n");
else
printf("Rejected, state = R\n");
return 0;
}
the above works better... it's only problem is that it rejects any input that is only 1 character...
example: 1
or 2
or 3
or +
or -
or v
does anybody see an easy way to fix either of these programs?