fork download
  1. #include <iostream>
  2. #include <limits>
  3.  
  4. int main()
  5. {
  6. using namespace std;
  7.  
  8. char c;
  9. int sum = 0;
  10. while ( cin >> c ) // read first character in line
  11. {
  12. if ( c == 'a' ) // end of input
  13. break;
  14.  
  15. int n;
  16. if (cin.unget() >> n) // putback in the stream the last read character and try to read an integer
  17. {
  18. sum += n;
  19. continue;
  20. }
  21.  
  22. cout << "Invalid input. Please try again.\n";
  23. cin.clear(); // failed to read an integer: reset the error flags
  24. cin.ignore(numeric_limits<streamsize>::max(), '\n'); // eat to the end of new-line
  25. }
  26.  
  27. cout << "The total sum is " << sum << ".\n";
  28. }
Success #stdin #stdout 0s 4524KB
stdin
1
2
invalid input
3
aignored
stdout
Invalid input. Please try again.
The total sum is 6.