cinfish.cpp 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // cinfish.cpp -- non-numeric input terminates loop
  2. #include <iostream>
  3. const int Max = 5;
  4. int main()
  5. {
  6. using namespace std;
  7. // get data
  8. double fish[Max];
  9. cout << "Please enter the weights of your fish.\n";
  10. cout << "You may enter up to " << Max
  11. << " fish <q to terminate>.\n";
  12. cout << "fish #1: ";
  13. int i = 0;
  14. while (i < Max && cin >> fish[i]) {
  15. if (++i < Max)
  16. cout << "fish #" << i+1 << ": ";
  17. }
  18. // calculate average
  19. double total = 0.0;
  20. for (int j = 0; j < i; j++)
  21. total += fish[j];
  22. // report results
  23. if (i == 0)
  24. cout << "No fish\n";
  25. else
  26. cout << total / i << " = average weight of "
  27. << i << " fish\n";
  28. cout << "Done.\n";
  29. // code to keep VC execution window open if q is entered
  30. // if (!cin) // input terminated by non-numeric response
  31. // {
  32. // cin.clear(); // reset input
  33. // cin.get(); // read q
  34. // }
  35. // cin.get(); // read end of line after last input
  36. // cin.get(); // wait for user to press <Enter>
  37. return 0;
  38. }