0

All I want to do, is prompt a user for a yes or no answer, and validate this to ensure they haven't typed something stupid.

I thought this would be a relatively straight forward task, however after many failed attempts at it myself, and looking around online, it seems everyone has a different opinion on the best way to do it.

Pseudocode

  1. Ask question

  2. prompt user

  3. check if input = yes or input = no

  4. if yes, do scenario a

  5. in no, do scenario b

  6. if invalid, return to point 2

Code

main.cpp

std::cout << "Do you have a user name? ("yes", "no"): ";
std::cin >> choice;
user.validation(choice);

if (choice == "yes")
{
// some code
}

if (choice == "no")
{
// some code
}

User.cpp

void User::validation(std::string choice)
{
    while (choice != "yes" && choice != "no")
    {       
        std::cout << "Error: Please enter 'yes' or 'no': ";
        std::cin >> choice;
        if (choice == "yes" && choice == "no")
        {
            break;
        }

    }
}

This works, up until they eventually type yes or no, when it jumps past if yes, and if no, straight onto the next part of the program

And I want to be able to call user.validation multiple times throughout the program to validate other yes/no questions

1
  • 1
    "I want to be able to call user.validation multiple times", what prevents you do it? Commented Dec 10, 2013 at 17:50

3 Answers 3

3

Try changing this

if (choice == "yes" && choice == "no")

For this

if (choice == "yes" || choice == "no")

Choice cannot be "yes" and "no" at the same time.

Sign up to request clarification or add additional context in comments.

2 Comments

This is not an answer to the question!
Also changed this thanks, I thought it should be || not &&. but before I changed it to &choice as shown by @PhillipKinkade, || did not work at all for some reason
2

You are not returning the corrected choice from validation():

void User::validation(std::string &choice) // <-- insert a & here

3 Comments

Thanks @Phillip Kinkade so this appears, on the surface at least, to have fixed my problem, but what is better practice, to use std::string compare() or to pass by reference (which is what I think you have shown above).
I prefer using == over std::string::compare(). Pass by reference is used a lot in C++. It depends on the situation if it's better or not.
thanks, will definitely do some research and reading up in this area
-1

C/C++ doesn't work like this for strings as the == operator isn't doing what you think it's doing for std::string objects and char* arrays. Use the std::string compare() method instead. Reference: http://www.cplusplus.com/reference/string/string/compare/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.