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

时间:2013-12-10 17:39:26

标签: c++ validation loops cin

我想做的就是提示用户回答是或否,并验证这一点以确保他们没有输入愚蠢的东西。

我认为这将是一项相对简单的任务,但是在我自己尝试多次尝试失败并在网上四处看看之后,似乎每个人对最佳方式都有不同的看法。

伪代码

  1. 提问

  2. 提示用户

  3. 检查输入=是或输入=否

  4. 如果是,请执行方案

  5. 否,请执行方案b

  6. 如果无效,请返回第2点

  7. 代码

    的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;
            }
    
        }
    }
    

    直到它们最终输入是或否,如果它跳过,如果是,如果不是,直接进入程序的下一部分

    我希望能够在整个程序中多次调用user.validation来验证其他是/否问题

3 个答案:

答案 0 :(得分:3)

尝试更改此

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

对于此

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

选择不能同时为“是”和“否”。

答案 1 :(得分:2)

您未从choice

返回更正后的validation()
void User::validation(std::string &choice) // <-- insert a & here

答案 2 :(得分:-1)

对于字符串,C / C ++不能像这样工作,因为==运算符没有按照你认为它为std :: string对象和char *数组做的事情。请改用std :: string compare()方法。参考:http://www.cplusplus.com/reference/string/string/compare/

相关问题