fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <limits>
  4. using namespace std;
  5. int main()
  6. {
  7. cout << "Please, enter a number\n";
  8. int n; // n is a number, it cannot be anything else
  9. // cin >> n reads a number. If it fails, it returns false,
  10. // so we check that condition in a loop:
  11. while( !(cin >> n) )
  12. {
  13. cout << "You need to enter a number\n";
  14. cin.clear(); // reset the error flags
  15. // here you still have unprocessed input. You have options:
  16. // 1. ignore:
  17. cin.ignore(numeric_limits<streamsize>::max(), '\n');
  18. // 2. read into a string
  19. // string str;
  20. // getline(cin, str);
  21. // 3. read into char (in a loop, since there may be many)
  22. // char c;
  23. // while(cin.get(c) && c != '\n')
  24. // {
  25. // }
  26. }
  27. cout << "Thank you for entering the number " << n << '\n';
  28. }
  29.  
Success #stdin #stdout 0.01s 2684KB
stdin
a
b
string
123
stdout
Please, enter a number
You need to enter a number
You need to enter a number
You need to enter a number
Thank you for entering the number 123