Answer to Exercise 96

| ANSWER TO EXERCISE 96
| The following implementation is limited to a format string 2x64 = 128 characters long, and six subsequent arguments. `%d` becomes a decimal number, `%e` an English one; `%c` a character, `%%` a (single) percentage sign and `%s` a string.
    Array printed_text table 64;
    Array printf_vals --> 6;
    [ Printf format p1 p2 p3 p4 p5 p6   pc j k;
      printf_vals-->0 = p1; printf_vals-->1 = p2; printf_vals-->2 = p3;
      printf_vals-->3 = p4; printf_vals-->4 = p5; printf_vals-->5 = p6;
      printed_text-->0 = 64; @output_stream 3 printed_text;
      print (string) format; @output_stream -3;
      j=printed_text-->0;
      for (k=2:k<j+2:k++)
      {   if (printed_text->k == '%')
          {   switch(printed_text->(++k))
              {   '%': print "%";
                  'c': print (char) printf_vals-->pc++;
                  'd': print printf_vals-->pc++;
                  'e': print (number) printf_vals-->pc++;
                  's': print (string) printf_vals-->pc++;
                  default: print "<** Unknown printf escape **>";
              }
          }
          else print (char) printed_text->k;
      }
    ];

Back to the exercise in section 33

Mechanically translated to HTML from third edition as revised 16 May 1997. Copyright © Graham Nelson 1993, 1994, 1995, 1996, 1997: all rights reserved.