word_count_functor.flex 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. %{
  2. // Copyright (c) 2001-2009 Hartmut Kaiser
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #include <boost/timer.hpp>
  7. #if defined(_WIN32)
  8. #include <io.h>
  9. #endif
  10. #define ID_WORD 1000
  11. #define ID_EOL 1001
  12. #define ID_CHAR 1002
  13. %}
  14. %%
  15. [^ \t\n]+ { return ID_WORD; }
  16. \n { return ID_EOL; }
  17. . { return ID_CHAR; }
  18. %%
  19. bool count(int tok, int* c, int* w, int* l)
  20. {
  21. switch (tok) {
  22. case ID_WORD: ++*w; *c += yyleng; break;
  23. case ID_EOL: ++*l; ++*c; break;
  24. case ID_CHAR: ++*c; break;
  25. default:
  26. return false;
  27. }
  28. return true;
  29. }
  30. int main(int argc, char* argv[])
  31. {
  32. int tok = EOF;
  33. int c = 0, w = 0, l = 0;
  34. yyin = fopen(1 == argc ? "word_count.input" : argv[1], "r");
  35. if (NULL == yyin) {
  36. fprintf(stderr, "Couldn't open input file!\n");
  37. exit(-1);
  38. }
  39. boost::timer tim;
  40. do {
  41. tok = yylex();
  42. if (!count(tok, &c, &w, &l))
  43. break;
  44. } while (EOF != tok);
  45. printf("lines: %d, words: %d, characters: %d\n", l, w, c);
  46. fclose(yyin);
  47. return 0;
  48. }
  49. extern "C" int yywrap()
  50. {
  51. return 1;
  52. }