regex_token_iterator_eg_1.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. *
  3. * Copyright (c) 12003
  4. * John Maddock
  5. *
  6. * Use, modification and distribution are subject to the
  7. * Boost Software License, Version 1.0. (See accompanying file
  8. * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. *
  10. */
  11. /*
  12. * LOCATION: see http://www.boost.org for most recent version.
  13. * FILE regex_token_iterator_example_1.cpp
  14. * VERSION see <boost/version.hpp>
  15. * DESCRIPTION: regex_token_iterator example: split a string into tokens.
  16. */
  17. #include <boost/regex.hpp>
  18. #include <iostream>
  19. using namespace std;
  20. #if defined(BOOST_MSVC) || (defined(__BORLANDC__) && (__BORLANDC__ == 0x550))
  21. //
  22. // problem with std::getline under MSVC6sp3
  23. istream& getline(istream& is, std::string& s)
  24. {
  25. s.erase();
  26. char c = static_cast<char>(is.get());
  27. while(c != '\n')
  28. {
  29. s.append(1, c);
  30. c = static_cast<char>(is.get());
  31. }
  32. return is;
  33. }
  34. #endif
  35. int main(int argc, const char*[])
  36. {
  37. string s;
  38. do{
  39. if(argc == 1)
  40. {
  41. cout << "Enter text to split (or \"quit\" to exit): ";
  42. getline(cin, s);
  43. if(s == "quit") break;
  44. }
  45. else
  46. s = "This is a string of tokens";
  47. boost::regex re("\\s+");
  48. boost::sregex_token_iterator i(s.begin(), s.end(), re, -1);
  49. boost::sregex_token_iterator j;
  50. unsigned count = 0;
  51. while(i != j)
  52. {
  53. cout << *i++ << endl;
  54. count++;
  55. }
  56. cout << "There were " << count << " tokens found." << endl;
  57. }while(argc == 1);
  58. return 0;
  59. }