在Linux下,使用
gets(cmd)
函數報錯:warning: the 'gets' function is dangerous and should not be used.
解決辦法:采用
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 ('\0') 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/