限制字符串长度

C++ - Limit the string length

本文关键字:字符串      更新时间:2023-10-16

我想创建一个允许用户创建密码和用户名的程序。密码长度为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 spacen";
    std::cout << "Password rules: must be 6+ characters longn";
    std::cout << "Must contain one uppercase letter and one number but no spacen";
    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;
}

由于您使用std::string,您可以在获得用户输入并检查大小是否在5 &10. 如果不是,只需重新向用户查询另一个密码。这最好在while循环中完成。下面是一些来自更高级别的代码示例:

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

你已经对用户名做了类似的事情,所以我有点困惑,如果你想问密码或不。

要限制字符输入,您需要检查输入长度是否在6到10个字符之间(包括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个字符

请添加您自己的答案

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