Use portable types in the C/C++ code generator
[ragel-jkt.git] / examples / atoi.rl
blob7164b68d9f22fd3ffc667c296c4652c6c1c7d81f
1 /*
2  * Convert a string to an integer.
3  */
5 #include <stdlib.h>
6 #include <string.h>
7 #include <stdio.h>
9 %%{
10         machine atoi;
11         write data;
12 }%%
14 long long atoi( char *str )
16         char *p = str, *pe = str + strlen( str );
17         int cs;
18         long long val = 0;
19         bool neg = false;
21         %%{
22                 action see_neg {
23                         neg = true;
24                 }
26                 action add_digit { 
27                         val = val * 10 + (fc - '0');
28                 }
30                 main := 
31                         ( '-'@see_neg | '+' )? ( digit @add_digit )+ 
32                         '\n';
34                 # Initialize and execute.
35                 write init;
36                 write exec;
37         }%%
39         if ( neg )
40                 val = -1 * val;
42         if ( cs < atoi_first_final )
43                 fprintf( stderr, "atoi: there was an error\n" );
45         return val;
49 #define BUFSIZE 1024
51 int main()
53         char buf[BUFSIZE];
54         while ( fgets( buf, sizeof(buf), stdin ) != 0 ) {
55                 long long value = atoi( buf );
56                 printf( "%lld\n", value );
57         }
58         return 0;