关于字符串:C-fgets和stdin的长度

C - fgets and length of stdin

我已经用C语言编写了一个程序,该程序可以让用户输入密码以允许他进入或不进入系统。 我正在使用方法fgets。 正确的密码是" letmein"。 这是代码:

现在,我要验证用户通过stdin输入的密码不超过8个字符。 因为程序是(没有空的if语句),所以即使用户输入" letmein0000000",也将授予该用户访问权限,因为fgets仅提取前七个字符。 现在,我只想授予用户访问权限(如果他输入" letmein")。 请问该怎么做?

附言 我必须使用fgets,因为这是我项目中的要求。


fgets()的文档中:

Reads at most count - 1 characters from the given file stream and stores them in str. The produced character string is always NULL-terminated. Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.

请求读取最多8个字符(这意味着将9作为第二个参数传递)。 如果用户输入的字符数超过7个,则可以捕获该字符。 通知用户失败,并跳过stdin中剩余的内容。 如果用户正确输入7并按回车键,则fgets()将停在换行符处。

检查返回值fgets(),以确保代码不会尝试处理统一缓冲区。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
char password[9];

if (fgets(password, 9, stdin))
{
    /* Strip new-line if present. */
    char* nl = strchr(password, '\
'
);
    if (nl) *nl = 0;

    if (strlen(password) > 7)
    {
        /* Password too long.
           Skip remaining input if necessary. */

        int c;
        while ((c = fgetc(stdin)) != EOF && c != '\
'
);
    }
    else if (0 == strcmp("letmein", password))
    {
        /* Good password. */
    }
    else
    {
        /* Incorrect password. */
    }
}