fork download
  1. #include <iostream>
  2. #include <istream>
  3. #include <limits>
  4. #include <string>
  5.  
  6. // These 2 functions will read a string/integer from an istream with error checking
  7. std::string ReadString(std::istream& is)
  8. {
  9. std::string result = "";
  10. while (!std::getline(is, result)) // do this until the user enters valid input
  11. {
  12. std::cin.clear(); // clear the error flags
  13. std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore the invalid data
  14. }
  15. return result;
  16. }
  17.  
  18. int ReadInt(std::istream& is)
  19. {
  20. int result = -1;
  21. while (!(is >> result))
  22. {
  23. std::cin.clear(); // clear the error flags
  24. std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore the invalid data
  25. }
  26. return result;
  27. }
  28.  
  29. int main(void)
  30. {
  31. std::cout << "Enter the racer's first name: ";
  32. std::string RacerName = ReadString(std::cin); // NOTE: should be a string
  33.  
  34. std::cout << "Enter the time (in minutes) at checkpoint 1: ";
  35. int CheckpointOne = ReadInt(std::cin);
  36. std::cout << "\nEnter the time (in minutes) at checkpoint 2: ";
  37. int CheckpointTwo = ReadInt(std::cin);
  38. std::cout << "\nEnter the time (in minutes) at checkpoint 3: ";
  39. int CheckpointThree = ReadInt(std::cin);
  40. std::cout << "\nEnter the time (in minutes) at checkpoint 4: ";
  41. int CheckpointFour = ReadInt(std::cin);
  42.  
  43. std::cout << "\nTimes for " << RacerName << std::endl
  44. << "\tCheckpoint 1: " << CheckpointOne << std::endl
  45. << "\tCheckpoint 2: " << CheckpointTwo << std::endl
  46. << "\tCheckpoint 3: " << CheckpointThree << std::endl
  47. << "\tCheckpoint 4: " << CheckpointFour << std::endl;
  48.  
  49. return 0;
  50. }
Success #stdin #stdout 0s 3420KB
stdin
Fred
1
2
3
4
stdout
Enter the racer's first name: Enter the time (in minutes) at checkpoint 1: 
Enter the time (in minutes) at checkpoint 2: 
Enter the time (in minutes) at checkpoint 3: 
Enter the time (in minutes) at checkpoint 4: 
Times for Fred
	Checkpoint 1:  1
	Checkpoint 2:  2
	Checkpoint 3:  3
	Checkpoint 4:  4