0

Hi, I am writing a function that needs to return either a R S or P. It works fine if what I am inputing is a R S or P. If something else is enter it acts funny. Any suggestions to help me out?

char getUserChoice ()
{
  char result;
  int again = 0;
  do {
    char x;  
    cout << "Please enter Rock, Paper, or Scissors: ";
    cin >> x;
    cin.ignore(1000, '\n');
    x = toupper(x);
    if (x == 'R') {
      result = 'R';
    } else if( x == 'P') {
      result = 'P';
    } else if (x == 'S') {
      result = 'S';
    } else {
      again = 1;
      cout << "Not a good choice. ";
    }
  } while (again);
  return (result);

Thanks

3
Contributors
5
Replies
6
Views
10 Years
Discussion Span
Last Post by kylcrow
0

assign zero to the variable "again" when the program shortly after enters the loop...(For example : Between the lines 5 - 6)

0

that doesnt work

It's working correctly...

Just write "again = 0" before the "char x" and trace your program again...

When you enter an invalid choice, "again" variable equals to 1 and program goes to the loop's starting.But if you don't assign 0 to the "again" variable here the loop's condition will always be true and this will be cause an infinite loop.

0

Instead of assigning x to result try just returning x (after ensuring it's a valid entry of course) ...also, instead of using an int value to control your loop use a boolean value...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.