Creating function for simple choices

Hey I am trying to simplify my code by creating a function which takes an input then checks whether it is "y" or "n" then outputs either 1 or 0 depending on the input. So far this is what I have

1
2
3
4
5
6
7
8
9
10
11
int Choice(string choice)
{
    while(choice.compare("n") != 0 && choice.compare("N") != 0 && choice.compare("y") != 0 && choice.compare("Y") != 0){
        cout << "Please enter a valid input either [y/n] thank you:" << endl;
        cin.clear(); cin.ignore(); cin >> choice;
    }
    cin.clear(); cin.ignore();
    if(choice.compare("n") == 0 || choice.compare("N") == 0) return 0;
    else if(choice.compare("y") == 0 || choice.compare("Y") == 0) return 1;
    else cerr << "Unknown error in choice function" << endl; exit(1);
}


And I call it in the program using
1
2
3
4
5
6
7
8
cout << "Do you wish to change the hubble type of any galaxies? [y/n]" << endl;
    cin >> choice;

    while(Choice(choice) == 1){
    ....
    cout << "Do you wish to change the hubble type of another galaxy? [y/n]" << endl;
    cin << choice;
    }


It compiles fine but displays some bizarre behaviour, I need to end the line twice in order for the program to continue and sometimes it just stops working (doesn't exit just appears to be stuck in a loop).

Only wondering if I have made some horrible mistake or written it poorly.

Thank you.
Last edited on
It compiles fine but displays some bizarre behaviour,
That's when you need to trace your program. It's character building to work thru it yourself, but in the end you need to run it in a debugger and step thru the code to ensure it's doing what you intended.
Cheers just wanted to check I didn't make some awful error or a programming nightmare.
Topic archived. No new replies allowed.