warning: the 'gets' function is dangerous and should not be used.的解决办法



在Linux下,使用

gets(cmd)

函数报错:warning: the 'gets' function is dangerous and should not be used.

 

解决办法:采用

#include<stdio.h>

char *fgets(char *restrict buf,int n,FILE *restrict fp)

返回值:成功,buf;失败或者文件结尾,NULL

例子:

fgets(cmd,100,stdin);//100为size

问题解决!

 

fgets从stdin中读字符,直至读到换行符或文件结束,但一次最多读size个字符。读出的字符连同换行符存入缓冲区cmd中。返回指向cmd的指针。

gets把从stdin中输入的一行信息存入cmd中,然后将换行符置换成串结尾符NULL。用户要保证缓冲区的长度大于或等于最大的行长。

 

gets的详细解释:

char * gets ( char * str );//Get string from stdin

Reads characters from stdin and stores them as a string into str  until a newline character ('n') or the End-of-File is reached.
The ending newline character ('n') is not included in the string.

A null character ('') is automatically appended after the last character copied to str to signal the end of the C string.

Notice that gets does not behave exactly as fgets does with stdin as argument: First, the ending newline character is not included with gets while with fgets it is. And second,gets does not let you specify a limit on how many characters are to be read, so you must be careful with the size of the array pointed by str to avoid buffer overflows.

 

说明:红色部分很好地解释了“the 'gets' function is dangerous and should not be used”这个warning的原因。

参考链接:http://www.cplusplus.com/reference/clibrary/cstdio/gets/

转自:http://blog.sina.com.cn/s/blog_6e64b2a601017ps2.html

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值