OOC:en:3.2 The Scanner

来自 ChinaUnix Wiki

In the main loop, once an input line has been read into buf[], it is passed to scan(), which for each call places the next input symbol into the variable token. At the end of a line token is zero:

   #include <ctype.h> 
   #include <errno.h> 
   #include <stdlib.h> 
   #include "parse.h" /* defines NUMBER */ 
   static double number; /* if NUMBER: numerical value */ 
   static enum tokens scan (const char * buf) 
   /* return token = next input symbol */ 
   { static const char * bp; 
     if (buf) 
       bp = buf; /* new input line */ 
     while (isspace(* bp)) 
       ++ bp; 
     if (isdigit(* bp) || * bp == ’.’) 
     { errno = 0; 
       token = NUMBER, number = strtod(bp, (char **) & bp); 
       if (errno == ERANGE) 
           error("bad value: %s", strerror(errno)); 
     } 
     else 
         token = * bp ? * bp ++ : 0; 
     return token; 
   }

We call scan() with the address of an input line or with a null pointer to continue work on the present line. White space is ignored and for a leading digit or decimal point we extract a floating point number with the ANSI-C function strtod(). Any other character is returned as is, and we do not advance past a null byte at the end of the input buffer.

个主工具