[英]fgets inside while loop for login validation
我在c中有此登录程序,它使用户最多可以尝试3次登录。 我正在使用fgets来避免缓冲区溢出,但是当我键入超过16个字符时,会发生这种情况:
输入登录名:
而不是只读取前16个“ a”。 这是我的代码:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int checkpasswd();
int main() {
int result;
result = checkpasswd();
if (result == 1)
printf("Password correct - Login approved\n");
else
printf("Invalid login and/or password\n");
return 0;
}
int checkpasswd(void) {
char name[16], passwd[16];
int correct = 0, attempts = 0;
while ((attempts != 3)&&(correct == 0)) {
printf("Enter login:");
fgets(name, sizeof(name), stdin);
printf("Enter password:");
fgets(passwd, sizeof(passwd), stdin);
if ((strncmp(name, "admin", strlen(name) - 1) == 0) && (strncmp(passwd, "secret", strlen(passwd) - 1) == 0))
correct = 1;
else
attempts++;
}
if (correct)
return 1;
else return 0;
}
首先,您应该检查fgets
返回什么。 如果失败,它将返回NULL
。
至于您的问题, fgets
函数不一定会读取整行。 如果您告诉fgets
最多读取16
字符(包括终止符),则fgets
将从输入中读取最多15个字符,然后将其余部分保留在缓冲区中。 它不会读,直到换行,并丢弃哪些不适合在缓冲区中。
要验证是否使用fgets
整行,请检查字符串中的最后一个字符是否为换行符。
为了在整个过程中为您提供帮助,您需要执行以下操作
if (fgets(name, sizeof name, stdin) == NULL)
{
// Error or end-of-file, either way no use in continuing
break;
}
if (strcspn(name, "\n") == strlen(name))
{
// No newline in string, there might be more to read in the input buffer
// Lets read and discard all remaining input in the input buffer until a newline
int c;
while ((c = fgetc(stdin)) != EOF && c != '\n')
{
}
// TODO: Should probably tell the user about this event
// Continue with next attempt
++attempts;
continue;
}
我确实建议您将其分解为一个单独的功能,您也可以将其重新用于读取密码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.