I'm pretty proud of this AskToPlayAgain Function! :)

So I wanted to make sure you could ONLY answer with y || Y || n || N
I think I made a decently compact function that only runs the code it needs to run.

I tried to only use 2 cases by doing this:

case: 'y' || 'Y':
case: 'n' || 'N':

But I got an error at the ‘n’ saying that that value already existed in another case. and I couldn’t get it solved.
So I went with the current option instead. What do you guys think? :smiley:

bool AskToPlayAgain()
{
    string Response = "";
    bool Again = true;
    bool IsValid = false;

    while (!IsValid)
    {
        
        cout << "Do you want to play again? y/n: ";
        getline(cin, Response);

        switch (Response[0])
        {
            case 'y':
            case 'Y':
                Again = true;
                IsValid = true;
                break;
            case 'n':
            case 'N':
                Again = false;
                IsValid = true;
                break;
            default: 
                cout << "That is not a valid answer! Please try again: " << endl << endl;
                IsValid = false;
                break;
        }


    }
    return Again;
}
2 Likes

You can lower the “Response” string and make things a little bit easier :stuck_out_tongue:

Sorry but I’m not sure what you mean by that XD
If you mean having the response string inside the switch then I’d rather not do that :slight_smile:

I like to set up my code this way: Variables Needed, Get Data needed, Use the data. So thats why the response string is grouped at the top together with the bools

I meant you’d only have to deal with two cases (y/n) if you convert to lowercase the string/char the user inputs.

Once you get the first char, try to apply this function tolower().

switch ((char) tolower(Response[0]))
    {
        case 'y':
            Again = true;
            IsValid = true;
            break;
        case 'y':
            Again = false;
            IsValid = true;
            break;
        default: 
            cout << "That is not a valid answer! Please try again: " << endl << endl;
            IsValid = false;
            break;
    }

Try this

http://www.cplusplus.com/reference/cctype/tolower/

1 Like

Ahhhh thanks! That works :slight_smile:

second case needs to be ‘n’, I guess …

1 Like

Yup

I do not intend to be rude and I hope that by now you already figured this out, but this is not good code. Again, don’t want to be rude, just want you to get better at coding.

It isn’t good because you replaced a simple, small and effective solution with an uglier, bigger, slower and unecessary one. For a more complex question to limit the possibilities of the the user is not only good, but frequently necessaire. In this case it is not.

If, even so, you’d like to do this, you could make it smaller and faster (unless user keeps ansering wrong forever) like this for example:

bool AskToPlayAgain()
{
	std::string Response;
	std::cout << "Do you want to play again? Y/n" << std::endl;
	getline(std::cin, Response);
	if (Response[0] == 'Y' || Response[0] == 'y' || Response[0] == NULL) {
        return true;
    } 
    else if(Response[0] == 'N' || Response[0] == 'n') {
        return false;
    }
    std::cout << "Invalid answer!" << std::endl;
    return AskToPlayAgain();
}

It would keep running the AskToPlayAgain function inside itself until it got a valid answer and would end returning it. But again, in this case I discourage it.

But it’s great that you went out of your way to do this by yourself and even used things like switch statements. Good work. :+1:

Don’t know if this will still be helpful for you but I hope it may help someone who passes by.

1 Like

You say you dont want to be rude, yet just one sentence later you start throwing the words Uglier, bigger, slower and unnecessary at me… I very much see this as rude!

you could have just said: “Hey dude, your code isn’t working as good as it could be, here’s another solution you could look at :)”… see thats way nicer and gets the same message across.

you also say

Followed by

without explaining WHY!!

I’m here doing my best to make the most game-like functionality I can make in this course that is all about making games, yet here you are bashing me into the ground without even explaining what I did wrong!!

In my opinion, your code looks way uglier. It’s one big, not easy to read, piece of code.

But I guess there is one good thing I got out of your “Not trying to be rude” rude message. I did not know I could just return AskToPlayAgain(), so thanks for that.

So one piece of advice. Saying “Not trying to be rude” does NOT make the things you say after that not rude. instead try keeping all the bad, discouraging words out. and when you tell someone he does something wrong, also tell them WHAT is wrong. Otherwise he can’t learn from his mistake!!

It really wasn’t my intention to offend you. I’ll try to make better answers in the future. But all that I said, I said to make you a better developer.

Your code really is “uglier, bigger, slower and unnecessary” compared to the lesson code. Knowing that now is gonna be good for your own development. Nobody is born knowing everything and is useful to be open to learn new things. As you keep coding and read good code from other people you’re going to enhance your skills.

I thought what I wrote was enough to clear out what was not good about it. The thing is: In this case you just want to get a simple answer from the user and give him a easy way to do this. The solution you came up with uses tools that are not necessary for the task. It is just making the code slower (because of things like the switch statement and the while loop) and bigger, the original solution uses only 4 lines of simple code that takes two seconds for reading, your code has several lines.

This is called recursion, a recursive function is a function that calls itself. It can be very useful. But it isn’t always wanted since every call uses up hardware resources. For example, calculating the fibonnaci sequence with a recursive function is bad because the number of calls grows exponentially (in this specific case!) using a lot more of CPU, RAM than an iterative solution. So be careful on when to use it.

The thing is: It is ok if your code isn’t very good in the beginning, if you keep trying to learn and evolve you’re gonna get better over time.

When you have the time (after finishing this course), read Clean Code and Code complete. And if you’re planning in becomming a real pro C++ developer also look for The C++ Programming Language book (it’s written by the creator of C++ himself).

By the way, I’m not saying for you to take all I say as the absolute truth. I’m just learning as well. But what I said was intended to help you.

I hope you’re advancing in the course and that this answer was useful. Consider my book recomendations. If you need to learn how to model 3D objects watch this guy’s videos. They are quite useful, he knows a lot about Blender. Unreal also has an YouTube channel, look for it and remember you can read the engine documentation to clear any doubts and enlarge your knowlegde about it.

Don’t give up nor let this episode discourage you, bye.

1 Like

I also recomend you to watch his videos. They are not all great nor he teaches how to program. But overall is a pretty solid channel and his videos might be useful to you.

Very nice that you tried to validate the player’s input!
Here is a suggestion to make the code a little more concise:

bool AskToPlayAgain()
{
  while (true)
  {
    cout << "Do you want to play again? y/n: ";

    string Response = "";
    getline(cin, Response);

    switch (Response[0])
    {
    case 'y': case 'Y': return true;
    case 'n': case 'N': return false;
    }
    cout << "That is not a valid answer! Please try again: " << endl << endl;
  }
}

Note that you can loop with “while(true)” and rely on “break” or “return” statements to break the loop, instead of a simple condition. This might look strange at first, but it is pretty common.

Also note that this does not work:

case 'y' || 'Y':
case 'n' || 'N':

And that is because the || operator is being calculated by the compiler and its result (1) is being used as the case specification, so both lines end up checking the same case. The correct way of doing an “OR” inside a switch statement in C++ is as you did later.

Also, be careful when calling a function from itself (recursion), as Felipe Liborio suggested. Recursion is extremely useful in several cases (some mathematical and logical problems are recursive in nature), but I personally would not use it as a way to retry an operation after a failed validation.

1 Like

True. Not to mention that recursion is a heavy memory consuming process.

Privacy & Terms