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

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

that doesnt work

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.

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...

ok thanks for all your help it works well now

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.