fork download
  1. #include <iostream>
  2. #include <limits>
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. float a, s{};
  8.  
  9. bool p{};
  10.  
  11. while((p = static_cast<bool>(std::cin >> a)) && a!=0) s+=a;
  12. std::cout << "a = " << a << "\tsum = " << s << '\n';
  13.  
  14. if(!p)
  15. {
  16. std::cout << "Input error. Repeat:> ";
  17.  
  18. std::cin.clear();
  19.  
  20. // clear till next possible number:
  21. //while(!std::isspace(std::cin.get()));
  22.  
  23. // clear till end of string:
  24. //while(std::cin.get() != '\n');
  25.  
  26. // clear till end of string (variant 2):
  27. //std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  28.  
  29. // should be same as previous, but it's not:
  30. std::cin.ignore(std::cin.rdbuf()->in_avail()); // why 0?
  31.  
  32. // syncronize i. e. drop till next possible number
  33. //std::cin.sync();
  34.  
  35. std::cin >> a; s+=a;
  36. std::cout << "a = " << a << "\tsum = " << s << '\n';
  37. }
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0s 4316KB
stdin
1.1 2.2 
3.3q 4.4 5.5
10
20
30
stdout
a = 0	sum = 6.6
Input error. Repeat:> a = 0	sum = 6.6