密码验证 - 空格

Password Validation - Spaces

本文关键字:空格 验证 密码      更新时间:2023-10-16

问题:不会退出循环。

我已经检查了一百万个站点,但无法弄清楚如何实现这一点。此循环不会因为 getline() 而退出。我需要 cin.ignore() 还是 cin.clear()?在尝试了所有可能的推导后,我无法让它工作。请帮忙..

while (strlen(u.username) < 6 || strlen(u.username) > 18||got_space==true)
{
    got_space = false;
    cout << "nError: Your username must be between 6 and 18 characters long and have no spaces. Please try again. (Press e to exit)n";
    cin >> u.username;
    if (strlen(u.username)<2 && tolower(u.username[0]) == 'e')
    {
        return;
    }
    cin.getline(u.username, USERNAME_SIZE); // Find whitespaces
    for (int c = 0; c < strlen(u.username); c++) // Check for spaces
    {
        if (isspace(u.username[c]))
        {
            got_space = true;
        }
    }
}

您在检查是否按下e cin中输入用户名,并在cin.getline(...)中键入。当你评论说

输入"1 1"给我 32 和 49(中间的空间)

输入 "1 1" 应该会导致输出整数49 32 49。因为你在输出语句中将字符转换为 int。在ASCII中字符1等效于整数49,字符' '空格)等价于整数32。既然你说你输入了"1 1",只得到了32和49,我就相信你开始在第一个cin输入用户名,然后继续输入下一个。这是一个修复程序:

while (strlen(u.username) < 6 || strlen(u.username) > 18||got_space==true)
{
    got_space = false;
    cout << "nError: Your username must be between 6 and 18 "
         << "characters long and have no spaces. "
         << "Please try again. (Press e then enter to exit)n";
    // remove this cin because it's messing up your code
    // cin >> u.username;
    // move the cin.getline(...) to here
    cin.getline(u.username, USERNAME_SIZE); // Find whitespaces        
    if (strlen(u.username)<2 && tolower(u.username[0]) == 'e')
    {
        return;
    }
    for (int c = 0; c < strlen(u.username); c++) // Check for spaces
    {
        if (isspace(u.username[c]))
        {
            got_space = true;
        }
    }
}

如果此代码运行,并且您遇到内存泄漏或分段错误,则已发布的代码无法找到错误,并且需要更多代码,就像在所有代码中一样。

既然它已被标记为C++,那么让我们用C++方法。

  1. 我更喜欢使用string::size()而不是strlen()(对于C风格的字符串)
  2. 要在字符串中查找空格,我们可以使用 string::find()。

以下是用于验证用户名输入的函数:

const unsigned validate(std::string& uname) {
    const unsigned s = uname.size();
    if(s < 6 || s > 18) return 1; 
    if(uname.find(" ") != std::string::npos) return 2;
    return 0;
}