0d354a00d2cceda65542958a297ff1593c3dab55
[external/ragel.git] / examples / atoi / atoi.rl
1 /*
2  * Convert a string to an integer.
3  */
4
5 #include <iostream>
6 #include <stdlib.h>
7 #include <stdio.h>
8
9 using namespace std;
10
11 %%{
12         machine atoi;
13         write data noerror;
14 }%%
15
16 int atoi( char *str )
17 {
18         char *p = str;
19         int cs, val = 0;
20         bool neg = false;;
21
22         %%{
23                 action see_neg {
24                         neg = true;
25                 }
26
27                 action add_digit { 
28                         val = val * 10 + (fc - '0');
29                 }
30
31                 main := 
32                         ( '-'@see_neg | '+' )? ( digit @add_digit )+ 
33                         '\n' @{ fbreak; };
34
35                 # Inintialize and execute.
36                 write init;
37                 write exec noend;
38         }%%
39
40         if ( neg )
41                 val = -1 * val;
42
43         if ( cs < atoi_first_final )
44                 cerr << "atoi: there was an error" << endl;
45
46         return val;
47 };
48
49
50 #define BUFSIZE 1024
51
52 int main()
53 {
54         char buf[BUFSIZE];
55         while ( fgets( buf, sizeof(buf), stdin ) != 0 ) {
56                 int value = atoi( buf );
57                 cout << value << endl;
58         }
59         return 0;
60 }