gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:08 25 4
gpt4 key购买 nike

根据 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/

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