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

user3001499
  • 811
  • 4
  • 16
  • 32
  • 1
    "I want to be able to call user.validation multiple times", what prevents you do it? – MeNa Dec 10 '13 at 17:50

3 Answers3

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.

Duncan Smith
  • 530
  • 2
  • 10
  • This is not an answer to the question! – MeNa Dec 10 '13 at 17:53
  • 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 – user3001499 Dec 10 '13 at 17:59
2

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

void User::validation(std::string &choice) // <-- insert a & here
Phillip Kinkade
  • 1,382
  • 12
  • 18
  • 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). – user3001499 Dec 10 '13 at 17:54
  • 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. – Phillip Kinkade Dec 10 '13 at 18:01
  • thanks, will definitely do some research and reading up in this area – user3001499 Dec 10 '13 at 18:06
-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/

S Farron
  • 561
  • 1
  • 5
  • 10