[C++] Using cin to get user input


/ Published in: C++
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8.  
  9. string input = "";
  10.  
  11. // How to get a string/sentence with spaces
  12. cout << "Please enter a valid sentence (with spaces):\n>";
  13. getline(cin, input);
  14. cout << "You entered: " << input << endl << endl;
  15.  
  16. // How to get a number.
  17. int myNumber = 0;
  18.  
  19. while (true) {
  20. cout << "Please enter a valid number: ";
  21. getline(cin, input);
  22.  
  23. // This code converts from string to number safely.
  24. stringstream myStream(input);
  25. if (myStream >> myNumber)
  26. break;
  27. cout << "Invalid number, please try again" << endl;
  28. }
  29. cout << "You entered: " << myNumber << endl << endl;
  30.  
  31. // How to get a single char.
  32. char myChar = { 0 };
  33.  
  34. while (true) {
  35. cout << "Please enter 1 char: ";
  36. getline(cin, input);
  37.  
  38. if (input.length() == 1) {
  39. myChar = input[0];
  40. break;
  41. }
  42.  
  43. cout << "Invalid character, please try again" << endl;
  44. }
  45. cout << "You entered: " << myChar << endl << endl;
  46.  
  47. cout << "All done. And without using the >> operator" << endl;
  48.  
  49. return 0;
  50. }

URL: http://www.cplusplus.com/forum/articles/6046/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.