我试图在Unix下使用gets函数在C语言中输入一个字符串,它不起作用!
它显示以下警告:
warning: the `gets' function is dangerous and should not be used.
Run Code Online (Sandbox Code Playgroud)
如果我运行程序,我不会得到输入字段.代码是
#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;
}
Run Code Online (Sandbox Code Playgroud)
有人帮我解决这个问题.我评论过我试过的所有可能性.谢谢!
raw scanf("%s")和gets()一样危险(两者都暴露在缓冲区溢出).您应该使用fgets(),这限制了字符串的长度.
gets()和fgets()之间的另一个区别是后者将'\n'字符串放入字符串中,虽然第一眼看上去很烦人,但您可以查看该行是否被截断.你应该做的是:
'\n''\n'用a 代替'\0',你就是金色的.getchar()循环调用直到你得到'\n'or EOF).