fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <sstream>
  5. #include <limits>
  6.  
  7. void do_without_exceptions()
  8. {
  9. std::istringstream in("3 4\n5 6\nbad line\n10 39\n100 1001\nbad line");
  10.  
  11. while (in.good())
  12. {
  13. int a, b;
  14. while (in >> a >> b)
  15. std::cout << a << " + " << b << " = " << a + b << '\n';
  16.  
  17. if (!in)
  18. {
  19. in.clear();
  20. in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  21. }
  22. }
  23. }
  24.  
  25. void do_with_exceptions()
  26. {
  27. auto exception_bits = std::istringstream::badbit |
  28. std::istringstream::failbit |
  29. std::istringstream::eofbit;
  30.  
  31. std::istringstream in("3 4\n5 6\nbad line\n10 39\n100 1001\nbad line");
  32. in.exceptions(exception_bits);
  33.  
  34. while (in.good())
  35. {
  36. try {
  37. int a, b;
  38. in >> a >> b;
  39. std::cout << a << " + " << b << " = " << a + b << '\n';
  40. }
  41.  
  42. catch (std::istream::failure& ex)
  43. {
  44. if (in.fail())
  45. {
  46. try {
  47. in.clear();
  48. in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  49. }
  50.  
  51. catch (std::istream::failure&)
  52. {
  53. }
  54. }
  55. }
  56. }
  57. }
  58.  
  59.  
  60. int main(int argc, char* argv[])
  61. {
  62. do_without_exceptions();
  63. do_with_exceptions();
  64. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
3 + 4 = 7
5 + 6 = 11
10 + 39 = 49
100 + 1001 = 1101
3 + 4 = 7
5 + 6 = 11
10 + 39 = 49
100 + 1001 = 1101