fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4.  
  5. int main()
  6. {
  7. while(true)
  8. {
  9. std::cout << std::endl;
  10.  
  11. std::string input;
  12. if(!std::getline(std::cin, input))
  13. {
  14. std::cout << "End of input" << std::endl;
  15. break;
  16. }
  17.  
  18. bool understood = false;
  19.  
  20. //Try to read it as a number
  21. {
  22. int n;
  23. if(std::istringstream(input) >> n)
  24. {
  25. std::cout << "You entered a number: " << n << std::endl;
  26. understood = true;
  27. }
  28. }
  29.  
  30. //Try to interpret it as a character
  31. if(input.length() == 1)
  32. {
  33. std::cout << "You entered a character: " << static_cast<int>(input[0]) << std::endl;
  34. understood = true;
  35. }
  36.  
  37. //Otherwise, just give back what we got
  38. if(!understood)
  39. {
  40. std::cout << "You entered something else: \"" << input << "\"" << std::endl;
  41. }
  42. }
  43. }
  44.  
Success #stdin #stdout 0s 3480KB
stdin
123
7
h
hello

stdout
You entered a number: 123

You entered a number: 7
You entered a character: 55

You entered a character: 104

You entered something else: "hello"

You entered something else: ""

End of input