我试着用gets函数在Unix下用C语言输入一个字符串,但不起作用!
它显示以下警告:
warning: the `gets' function is dangerous and should not be used.如果我运行这个程序,我得不到输入域。代码是
#include<stdio.h>
int main()
{
int i;
char ch,newfile[10],content[100];
FILE *create;
printf("Enter New File Name to Create : ");
scanf("%s",newfile);
create=fopen(newfile,"w+");
printf("\nEnter Contents for %s : ",newfile);
//fgets(content,sizeof content,stdin);
//scanf("%s",&content);
//gets(content);
for(i=0;i<100;i++)
{
if(content[i]!='\0')
{
ch=content[i];
putc(ch,create);
}
else
break;
}
printf("\nYour File Is Created\n");
return 0;
} 有人好心帮我解决这个问题。我已经评论了我尝试过的所有可能性。谢谢!
发布于 2013-04-23 14:14:37
原始scanf("%s")和gets()一样危险(两者都暴露在缓冲区溢出中)。您应该改用fgets(),因为它限制了字符串的长度。
gets()和fgets()之间的另一个区别是后者将'\n'放在字符串中,虽然乍一看很烦人,但它允许您查看行是否被截断。你应该做的是:
'\0'替换'\n'就可以了。getchar(),直到获得'\n'或EOF)。https://stackoverflow.com/questions/16162161
复制相似问题