What can I use for input conversion instead of scanf?

前端 未结 8 1125
悲哀的现实
悲哀的现实 2020-11-22 13:27

I have very frequently seen people discouraging others from using scanf and saying that there are better alternatives. However, all I end up seeing is either

8条回答
  •  野性不改
    2020-11-22 13:41

    Here is an example of using flex to scan a simple input, in this case a file of ASCII floating point numbers that might be in either US (n,nnn.dd) or European (n.nnn,dd) formats. This is just copied from a much larger program, so there may be some unresolved references:

    /* This scanner reads a file of numbers, expecting one number per line.  It  */
    /* allows for the use of European-style comma as decimal point.              */
    
    %{
      #include 
      #include 
      #include 
      #ifdef WINDOWS
        #include 
      #endif
      #include "Point.h"
    
      #define YY_NO_UNPUT
      #define YY_DECL int f_lex (double *val)
    
      double atofEuro (char *);
    %}
    
    %option prefix="f_"
    %option nounput
    %option noinput
    
    EURONUM [-+]?[0-9]*[,]?[0-9]+([eE][+-]?[0-9]+)?
    NUMBER  [-+]?[0-9]*[\.]?[0-9]+([eE][+-]?[0-9]+)?
    WS      [ \t\x0d]
    
    %%
    
    [!@#%&*/].*\n
    
    ^{WS}*{EURONUM}{WS}*  { *val = atofEuro (yytext); return (1); }
    ^{WS}*{NUMBER}{WS}*   { *val = atof (yytext); return (1); }
    
    [\n]
    .
    
    
    %%
    
    /*------------------------------------------------------------------------*/
    
    int scan_f (FILE *in, double *vals, int max)
    {
      double *val;
      int npts, rc;
    
      f_in = in;
      val  = vals;
      npts = 0;
      while (npts < max)
      {
        rc = f_lex (val);
    
        if (rc == 0)
          break;
        npts++;
        val++;
      }
    
      return (npts);
    }
    
    /*------------------------------------------------------------------------*/
    
    int f_wrap ()
    {
      return (1);
    }
    

提交回复
热议问题