简体   繁体   English

用户输入的C ++字符串验证

[英]c++ string validation for user input

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 如果是,请执行方案a

  5. in no, do scenario b 否,情况b

  6. if invalid, return to point 2 如果无效,则返回第2点

Code

main.cpp 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 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 我希望能够在整个程序中多次调用user.validation来验证其他是/否问题

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. C / C ++对于字符串不起作用,因为==运算符没有执行您认为对std :: string对象和char *数组所做的事情。 Use the std::string compare() method instead. 请改用std :: string compare()方法。 Reference: http://www.cplusplus.com/reference/string/string/compare/ 参考: http : //www.cplusplus.com/reference/string/string/compare/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM