summaryrefslogtreecommitdiff
path: root/examples/atoi.rl
blob: 7164b68d9f22fd3ffc667c296c4652c6c1c7d81f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
 * Convert a string to an integer.
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

%%{
	machine atoi;
	write data;
}%%

long long atoi( char *str )
{
	char *p = str, *pe = str + strlen( str );
	int cs;
	long long val = 0;
	bool neg = false;

	%%{
		action see_neg {
			neg = true;
		}

		action add_digit { 
			val = val * 10 + (fc - '0');
		}

		main := 
			( '-'@see_neg | '+' )? ( digit @add_digit )+ 
			'\n';

		# Initialize and execute.
		write init;
		write exec;
	}%%

	if ( neg )
		val = -1 * val;

	if ( cs < atoi_first_final )
		fprintf( stderr, "atoi: there was an error\n" );

	return val;
};


#define BUFSIZE 1024

int main()
{
	char buf[BUFSIZE];
	while ( fgets( buf, sizeof(buf), stdin ) != 0 ) {
		long long value = atoi( buf );
		printf( "%lld\n", value );
	}
	return 0;
}