C ++ - 限制字符串长度

时间:2016-11-16 02:58:13

标签: c++

我想创建一个允许用户创建密码和用户名的程序。但是,密码必须介于6到10个字符之间。我如何限制字符输入?另外,如果我希望密码包含大写字母怎么办?

到目前为止看看这个程序,让你知道我想要做什么(注意:我知道程序本身显然未完成但我只是想给你一个视觉效果):

#include <iostream>
#include <string>

int main(int argc, const char * argv[]) {
    // insert code here...

    std::cout << "--------------------------------------------------------------\n";
    std::cout << "          Welcome to the ECE!! Password Proram!\n";
    std::cout << "Username rules: must be 5-10 characters long with no space\n";
    std::cout << "Password rules: must be 6+ characters long\n";
    std::cout << "Must contain one uppercase letter and one number but no space\n";
    std::cout << "--------------------------------------------------------------\n";

    //Let's get our password!
    std::string username;
    std::string password;
    const int

    //use a do while loop for input validation
    do {    
        std::cout << "Enter your username: ";
        std::cin >> username;                       //add input validation               
    } while ();

    std::cout << "Enter your password:";
    std::cin >> password;    
    return 0;
}

3 个答案:

答案 0 :(得分:0)

要限制字符输入,您需要检查输入长度是否介于6到10个字符之间。 (我不知道在10个字符后切断输入的方法)你会做类似

的事情
start: // A label to direct where the program should go when goto is called.
while(password.length() > 10 || password.length() < 5)
{
    std::cout << "The password must be between 5 and 10 characters inclusive." << endl;
    std::cin >> password;
}
// To check if there is a capital letter
bool foundUpperLetter = false;
for(int i = 0; i < password.length(); i++)
{
    if(foundUpperLetter == true)
        break;
    if('A' <= password[i] && password[i] <= 'Z')
        foundUpperLetter = true;
}
if(!foundUpperLetter)
{
    std::cout << "You did not include an uppercase letter in your input. Please try again." << endl;
    goto start; // Will make the program go back to label start.
}

您还可以向上一部分添加更多代码,以检查密码所需的其他属性。

资料来源:为学校和个人享受编码15个月。如果有更好的办法或者你知道如何在10个字符后切断输入,请添加你自己的答案

答案 1 :(得分:0)

由于你正在使用std :: string,你可以在获得用户输入并检查大小是否在5&amp; 5的范围内之后使用password.size()。 10.如果不是,只需重新查询用户另一个密码即可。这最好在while循环中完成。 以下是更高级别的一些代码的示例:

do{
    std::cout << "Enter your password:";
    std::cin >> password;
}while (password.size() < 6 || password.size() > 10)

您已经使用用户名做了类似的事情,所以如果您打算询问密码,我会感到有点困惑。

答案 2 :(得分:0)

在概念层面:您可以接受字符串输入,检查长度和其他属性(即包含一个大写字母),将其用于进一步操作。如果不符合以下条件,请要求用户重新输入信息。

相关问题