我是初学程序员。我正在编写一个程序来检查密码是否为c-string,长度是6到10个字符。如果不是,则用户必须重新输入密码才能满足要求。对于程序的输入验证部分,当密码少于6个字符时它起作用 - 告诉用户重新输入密码。但是,当它超过10个字符长时,它不会显示超过10个字符长的错误。我该如何解决这个问题?感谢您的输入。
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const int SIZE = 12; // Maximum size for the c-string
char pass[SIZE]; // to hold password c-string.
int length;
// get line of input
cout << "Enter a password between 6 and " << (SIZE - 2) << "characters long:\n";
cin.getline(pass, SIZE);
length = strlen(pass);
while (length < 6 || length > 10)
{
cout << "Error: password is not between 6 and " << (SIZE - 2) << " characters long.\n"
<< "Enter the password again: ";
cin.getline(pass, SIZE);
length = strlen(pass);
}
return 0;
}
答案 0 :(得分:2)
我不确定你为什么要使用cstrings,因为正常的字符串也能正常工作。以下是我将如何重写它:
Root: HKCR; Subkey: ".tgt"; ValueData: "{#MyAppName}"; Flags: uninsdeletevalue; ValueType: string; ValueName: ""
Root: HKCR; Subkey: "{#MyAppName}"; ValueData: "Program {#MyAppName}"; Flags: uninsdeletekey; ValueType: string; ValueName: ""
Root: HKCR; Subkey: "{#MyAppName}\DefaultIcon"; ValueData: "{app}\{#MyAppExeName},0"; ValueType: string; ValueName: ""
Root: HKCR; Subkey: "{#MyAppName}\shell\open\command"; ValueData: """{app}\{#MyAppExeName}"" ""%1"""; ValueType: string; ValueName: ""
如果您需要在数组中输入密码,请使用:
string pass;
cout << "Enter password: ";
cin >> pass;
while (pass.length() > 10 || pass.length() < 6)
{
cout << "Not the right length, try again: ";
cin >> pass;
}
然而,这是未经测试的,但它应该有用。
答案 1 :(得分:1)
您不允许超过10个字符的密码。 C字符串以空值终止,因此10个字符加上空字节为11.您将只获得10个长度。附:我建议
.chart-content {
width: 100vw;
height: 100vh;
background: tan;
border-radius: 100vw;
position: absolute;
z-index: -1;
}
更清楚地知道常量是密码的最大长度
修改
我同意其他帖子,std :: string是一个更好的选择,但它也很重要,特别是对于一个更重要的人来理解问题而不仅仅是接受解决方案,因为这是应该做的事情
答案 2 :(得分:0)
const int SIZE = 11;
char password[SIZE];
password
无法存储超过11个字符(最后一个字符是NULL终止符'\0'
)。
cin.getline(password, SIZE);
你没有办法得到比你要求更多的东西,SIZE
。
快速解决方案是将其更改为
char password[SIZE + 1];
。为什么?因为它能够存储比你想要的更多的字符,所以你可以检查输入是否太长。
当然,您还必须将cin.getline(...
更改为cin.getline(password, SIZE + 1);
。
您忘了更新length
中的if
。我建议做一些这样的事情,让它更清洁:
const int SIZE = 11;
char password[SIZE + 1];
while (true) // Create a loop
{
cout << "Enter a password between 6 and "
<< (SIZE - 1) << " characters long:\n";
// If bad input, discard the remaining input
if (!cin.getline(password, SIZE + 1))
{
cin.clear();
cin.ignore(INT_MAX, '\n');
}
int length = strlen(password);
// Check input validation if password is bet. 6 and 10 characters
if (length < 6 || length > 10)
{
cout << "Password is not between 6 " << (SIZE - 1)
<< " characters.\n Please enter your password again:\n";
}
else { break; } // Break loop if input vaild
}