密码验证 - 空格
Password Validation - Spaces
问题:不会退出循环。
我已经检查了一百万个站点,但无法弄清楚如何实现这一点。此循环不会因为 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++方法。
- 我更喜欢使用string::size()而不是strlen()(对于C风格的字符串)
- 要在字符串中查找空格,我们可以使用 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;
}
相关文章:
- 2D数组来自文本输入,中间有空格
- 正在尝试了解输入验证循环
- 如何在C++中检查2D数组中负值的输入验证
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- LibGit2 SSH身份验证失败
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- Vulkan验证层不断在VkQueuePresentKHR()上抛出图像布局错误
- constexpr上下文中std::initializer_list的验证
- 如何在c++中使用system()来运行包含空格的python脚本
- basic_string的前导/尾部不区分空格的特征
- 移除前面有空格的前2个字符串
- 正在验证c++中用户的整数输入
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 加密++验证大文件签名
- C++卡验证问题
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 仅 C++ 字母和空格输入验证
- 密码验证 - 空格
- 空格分隔整数的验证