fork(1) download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. int main()
  5. {
  6. std::string input;
  7.  
  8. while (std::cin.good()) {
  9. std::cout << "Direction? (n/s/e/w/q): ";
  10. std::getline(std::cin, input);
  11.  
  12. // if input is empty, input[0] would be undefined behavior.
  13. if (input.empty())
  14. continue;
  15.  
  16. switch (input[0]) // check the first character only
  17. {
  18. case 'n':
  19. std::cout << "You have entered a dark room.\n";
  20. break; // escape the switch, not the loop.
  21.  
  22. case 'e':
  23. case 's': // no break, 'e' falls thru
  24. case 'w': // still no break, 'e' and 's' fall thru
  25. std::cout << "You can't go that way.\n";
  26. break;
  27.  
  28. case 'q':
  29. std::cout << "bye!\n";
  30. return 0;
  31. break;
  32.  
  33. default:
  34. std::cout << "I asked you to type n, s, e, w or q, but you typed " << input << ".\n";
  35. break;
  36. }
  37. }
  38.  
  39. return 0;
  40. }
  41.  
  42.  
Success #stdin #stdout 0s 3476KB
stdin
n
w
e
s
help
q
stdout
Direction? (n/s/e/w/q): You have entered a dark room.
Direction? (n/s/e/w/q): You can't go that way.
Direction? (n/s/e/w/q): You can't go that way.
Direction? (n/s/e/w/q): You can't go that way.
Direction? (n/s/e/w/q): I asked you to type n, s, e, w or q, but you typed help.
Direction? (n/s/e/w/q): bye!