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
Ask question
prompt user
check if input = yes or input = no
if yes, do scenario a
in no, do scenario b
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
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.
您没有从validation()
返回正确的choice
:
void User::validation(std::string &choice) // <-- insert a & here
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/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.