fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. using namespace std;
  5.  
  6. template<typename T>
  7. void Get(T& toSet, std::string prompt) // read from cin
  8. {
  9. std::string nextIn;
  10. cout << prompt;
  11. getline(cin >> std::ws, nextIn);
  12. istringstream inStream(nextIn);
  13. while(cin && !(inStream >> toSet))
  14. {
  15. inStream.clear();
  16. cout << "Invalid Input. Try again.\n" << prompt;
  17. getline(cin >> std::ws, nextIn);
  18. inStream.str(nextIn);
  19. }
  20. if (!cin)
  21. {
  22. cerr << "\nFailed to get proper input. Exiting\n";
  23. exit(1);
  24. }
  25. }
  26.  
  27. int main()
  28. {
  29. string name;
  30. int num1 = -1;
  31. cout << "\nHello!\n";
  32. Get(name, "\nTell me your name?:");
  33. cout << "\nWell well well, if it isn't "<< name << "!\n";
  34. Get(num1, std::string("\nEnter a NUMBER, ") + name + ": ");
  35. cout << "\nYou entered number: " << num1 << std::endl;
  36.  
  37. return 0;
  38. }
Success #stdin #stdout 0s 3284KB
stdin
Kevin ferer 
asdf asdfasdf  asdf

asd
 '

a   asdf asdfsdfd d
100
stdout
Hello!

Tell me your name?:
Well well well, if it isn't Kevin!

Enter a NUMBER, Kevin: Invalid Input. Try again.

Enter a NUMBER, Kevin: Invalid Input. Try again.

Enter a NUMBER, Kevin: Invalid Input. Try again.

Enter a NUMBER, Kevin: Invalid Input. Try again.

Enter a NUMBER, Kevin: 
You entered number: 100