在Linux下,使用
gets(cmd)
函數(shù)報錯:warning: the 'gets' function is dangerous and should not beused.
解決辦法:采用
fgets(cmd,100,stdin);//100為size
問題解決!
fgets從stdin中讀字符,直至讀到換行符或文件結(jié)束,但一次最多讀size個字符。讀出的字符連同換行符存入緩沖區(qū)cmd中。返回指向cmd的指針。
gets把從stdin中輸入的一行信息存入cmd中,然后將換行符置換成串結(jié)尾符NULL。用戶要保證緩沖區(qū)的長度大于或等于最大的行長。
gets的詳細(xì)解釋:
char * gets ( char * str );//Get string fromstdin
Reads characters from stdin and stores them as a string intostr
The ending newline character ('\n') is not included in thestring.
A null character ('\0') is automatically appended after the lastcharacter copied to str to signal the end of the C string.
Notice that gets does notbehave exactly as fgets does with stdin as argument: First,the ending newline character is not included with gets while withfgets it is. And second, gets does not let you specify a limit on howmany characters are to be read, so you must be careful with thesize of the array pointed by str to avoid bufferoverflows.
說明:紅色部分很好地解釋了“the'gets' function is dangerous and should not beused”這個warning的原因。
參考鏈接:http://www.cplusplus.com/reference/clibrary/cstdio/gets/