fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <limits>
  4. #include <cassert>
  5.  
  6. struct X { int a_, b_; };
  7.  
  8. std::istream& operator>>(std::istream& is, X& x)
  9. {
  10. char c;
  11. if (is >> x.a_ && is.get(c))
  12. if (c == '\n')
  13. {
  14. x.b_ = 1;
  15. return is;
  16. }
  17. else if (c == '/' && is >> x.b_)
  18. return is;
  19. else
  20. is.setstate(std::istream::failbit);
  21. return is;
  22. }
  23.  
  24. int main()
  25. {
  26. std::istringstream iss("5\n10/2\n3xyz\n8/17\n9\nNOWAY\n42/4\n");
  27. X x;
  28. while (iss >> x)
  29. std::cout << "parsed " << x.a_ << '/' << x.b_ << '\n';
  30. iss.clear();
  31.  
  32. std::string remnants;
  33. assert(getline(iss, remnants));
  34. std::cout << "parsing failed, line remnants for '" << remnants << "'\n";
  35. // normally would prefer following to getline above...
  36. // iss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  37.  
  38. iss.exceptions(std::istream::failbit);
  39. while (iss)
  40. try
  41. {
  42. while (iss >> x)
  43. std::cout << "also parsed " << x.a_ << '/' << x.b_ << '\n';
  44. }
  45. catch (const std::exception& e)
  46. {
  47. std::cout << "caught exception " << e.what() << '\n';
  48. if (!iss.eof())
  49. {
  50. iss.clear();
  51. iss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  52. }
  53. }
  54. std::cout << "eof " << iss.eof() << ", bad " << iss.bad()
  55. << ", fail " << iss.fail() << '\n';
  56. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
parsed 5/1
parsed 10/2
parsing failed, line remnants for 'yz'
also parsed 8/17
also parsed 9/1
caught exception basic_ios::clear
also parsed 42/4
caught exception basic_ios::clear
eof 1, bad 0, fail 1