gpt4 book ai didi

C 函数 (fgets) 缓解

转载 作者:太空宇宙 更新时间:2023-11-04 07:51:53 26 4
gpt4 key购买 nike

我不明白为什么使用 fgets 获取输入总是给我的程序“密码错误”。

但是,当我使用 gets() 时,比如 gets(array); 它起作用了。

预期输出:当密码错误时,打印“Wrong Passwor”,对于正确的密码,让我看看我的“访问已被授予”:

#include <stdio.h>
#include <string.h>

int main(void)
{
int n=15;
char array[n];
int pass = 0;

printf("\n Enter the password : \n");
fgets(array, n, stdin);

if(strncmp(array, "password",n))
{
printf ("\n Wrong Password \n");
}
else
{
printf ("\n Correct Password \n");
pass = 1;
}
if(pass)
{
/* Now Give root or admin rights to user*/
printf ("\n Root privileges given to the user \n");
}
return 0;
}

最佳答案

这里的要点是,fgets() 读取并存储尾随换行符,检查 man page对于 fgets()

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. [...]

您需要在比较之前删除尾随的换行符。

你可以清理输入,使用

 array[strcspn(array, "\n")] = 0;

从输入中删除尾随的换行符。

关于C 函数 (fgets) 缓解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53262648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com