gets不能用
#include
#include
int main()
{
int i=0;
char a[31];
gets(a);
while(a[i]!='#')
{
if(a[i]>='A'&&a[i]<='Z')
a[i]=a[i]-'A'+'a';
else if(a[i]>='a'&&a[i]<='z')
a[i]=a[i]-'a'+'A';
i++;
}
for(i=0;a[i]!='#';i++)
{
printf("%c",a[i]);
}
return 0;
}
a.c: In function ‘main’:
a.c:7:4: warning: ‘gets’ is deprecated [-Wdeprecated-declarations]
gets(a);
^~~~
In file included from /usr/include/stdio.h:862:0,
from a.c:1:
/usr/include/x86_64-linux-gnu/bits/stdio2.h:232:1: note: declared here
gets (char *__str)
^~~~
a.c:7:4: warning: ignoring return value of ‘gets’, declared with attribute warn_unused_result [-Wunused-result]
gets(a);
^~~~~~~
/tmp/cc3oWUvp.o: In function `main':
a.c:(.text.startup+0x22): warning: the `gets' function is dangerous and should not be used.
gets_s函数对应头文件<stdio.h>
原型:char *gets_s(char *buffer,size_t sizeInCharacters);
调用形式:gets_s(buffer,sizeInCharacters) ;
在2011年12月,ANSI 采纳了 ISO/IEC 9899:2011 标准,标准中删除了 gets()函数,使用一个新的更安全的函数gets_s()替代。
//摘自百度百科
#include <stdio.h>//gets_s()用法
#define CH 20
int main(void)
{
char ch[CH];
printf("请输入你的名字:\n");
gets_s(ch,CH); //这里不能用gets_s(ch);
printf("这是你的名字:%s\n", ch);
return 0;
}
gets函数由于没有指定输入字符的大小,限制输入缓冲区得大小,如果输入的字符大于定义的数组长度,会发生内存越界,堆栈溢出。后果非常严重!
用gets_s(a,30)