C字符串,如何确定字符长度是否在6到10之间

C-strings, how to determine if the characters are between 6 and 10 long?

本文关键字:是否 之间 字符串 何确定 字符      更新时间:2023-10-16

我是初级程序员。我正在编写一个程序来检查密码(作为c字符串)的长度是否在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;
}

我不知道为什么要使用cstrings,因为普通字符串也能正常工作。以下是我将如何重写它:

string pass;
cout << "Enter password: ";
cin  >> pass;
while (pass.length() > 10 || pass.length() < 6)
{
  cout << "Not the right length, try again: ";
  cin  >> pass;
}

如果您需要在数组中输入密码,请使用以下命令:

//To use the c_string version of it, type 
pass.c_str();
return 0;

然而,这是未经测试的,但它应该有效。

您不允许密码超过10个字符。C字符串以null结尾,因此10个字符加上null字节等于11。你只会得到一个10长度。附言:我建议

    char password[SIZE+2]

更清楚地表明,常数是密码的最大长度

编辑

我同意其他帖子中的观点,即std::string是一个更好的选择,但这也很重要,尤其是对于一个大人物来说,理解问题而不仅仅是接受解决方案,因为这是应该做的事情

const int SIZE = 11;
char password[SIZE];

password不可能存储超过11个字符(其中最后一个字符是NULL终止符'')。

cin.getline(password, SIZE);

你不可能得到比你要求的更多的东西,这就是SIZE

一个快速的解决方案是将其更改为char password[SIZE + 1];。为什么?因为它将能够存储比您想要的更多的字符,从而允许您检查输入是否过长。

当然,您还必须将cin.getline(...更改为cin.getline(password, SIZE + 1);

你也忘了在那个if中更新你的length。我建议这样做,让它更干净:

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
}
相关文章: