C函数(fgets)缓解 [英] C function (fgets) mitigation

查看:63
本文介绍了C函数(fgets)缓解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么使用 fgets 进行输入总是为我的程序提供错误密码".

I can't understand why taking the input using fgets always gives me "Wrong password" for my program.

但是,当我使用 gets()时,就像 gets(array); 一样.

However, when I use gets(), like gets(array); it works.

预期的输出:当密码错误时,显示"Wrong Passwor",对于正确的密码,请让我看看我的访问权限被授予":

Expected outputs: when the password is wrong, prints "Wrong Passwor" and for correct one, let me see my "access is granted":

#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()读取并存储结尾的换行符,请检查

The point here is, fgets() reads and stores the trailing newline, check the man page for fgets().

fgets()从流中读取最多小于大小的字符,并将其存储到 s 指向的缓冲区中.在 EOF 或换行符之后停止读取.如果读取了换行符,则会将其存储在缓冲区中. [...]

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. [...]

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

You need to remove that trailing newline before the comparison.

您可以使用

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

从输入中删除尾随换行符.

to remove the trailing newline from the input.

这篇关于C函数(fgets)缓解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆