c - 为什么使用 fgets() 而不是 gets() 时行为不同

标签 c fgets gets

根据 gcc 警告:

the `gets' function is dangerous and should not be used

我尝试使用 fgets() 但它并没有在我的代码中出现,因为您可能会在下面的代码末尾看到两者的输出。有人可以告诉我我在做什么错误(如果有的话)吗?

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

#define size 128

int Table[size];

/****ShiftTable Function Declaration****/
void ShiftTable(char Pattern[]);

/****Horspool Function Declaration****/
int Horspool(char Pattern[],char Text[]);

/****Main Function****/
int main()
   {
    char Text[100],Pattern[100];
    int pos;

    printf("Enter the Text : ");
    gets(Text);                    //Works fine
    //fgets(Text,100,stdin);       //Does not work

    printf("\nEnter the Pattern: ");
    gets(Pattern);                 //Works fine
    //fgets(Pattern,100,stdin);    //Does not Work

    pos=Horspool(Pattern,Text);

    if(pos==-1)
            printf("\nPattern Not Found!\n\n");
    else
        printf("\nPattern Found at %d position.\n\n",pos+1);        

    return 0;
   }

/****Horspool Function Definition****/
int Horspool(char Pattern[],char Text[])
   {
    int m,n,i,k;

    n=strlen(Text);
    m=strlen(Pattern);

    ShiftTable(Pattern);

    i=m-1;

    while(i<n)
         {
        k=0;
        while(k<m && (Text[i-k]==Pattern[m-1-k]))  k++;

        if(k==m)   return i-m+1;

        i+=Table[Text[i]];
         }

    return -1;
    }

/****ShifTable Function Definition****/
void ShiftTable(char Pattern[])
    {
    int i,m;
    m=strlen(Pattern);

    for(i=0;i<size;i++)
        Table[i]=m;

    for(i=0;i<m-1;i++)
        Table[Pattern[i]]=m-1-i;
    }

输出:

当我使用 gets()

majid@majid-K53SC:~ $ ./a.out

Enter the Text : BANGALORE IS GARDEN CITY

Enter the Pattern: GARDEN

Pattern Found at 14 position.

当我使用 fgets()

majid@majid-K53SC:~ $ ./a.out

Enter the Text : BANGALORE IS GARDEN CITY

Enter the Pattern: GARDEN

Pattern Not Found!

最佳答案

fgets 消耗换行符(输入字符串后按Enter)并将其存储在Text中,而gets 没有。你需要 strip the newline character off来自文本

因此,在两次调用 gets 之后,

Text = "BANGALORE IS GARDEN CITY"
Pattern = "GARDEN"

fgets 的情况下,

Text = "BANGALORE IS GARDEN CITY\n"
Pattern = "GARDEN\n"

关于c - 为什么使用 fgets() 而不是 gets() 时行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30724675/

相关文章:

c - 在 C 中设置 open() 系统调用的权限

c++ - C++ 中的 SAL_CALL 是什么?

c - 在 C 中比较字符串时,fgets 比 scanf 更有效吗?

c - 从 fgets() 输入中删除尾随换行符

c - 无法使用 fgets() 函数读取循环结构内的字符串

c++ - 如何解析以下字符串

c - C 中的嵌套 Lua 元表

PHP 脚本越来越慢(文件阅读器)

ruby - 如何超时gets.chomp

c - 从用户那里获取输入 - 不起作用