頭文件:#include <stdio.h>
gets()函數用於從緩沖區中讀取字符串,其原型如下:
char *gets(char *string);
gets()函數從流中讀取字符串,直到出現換行符或讀到文件尾為止,最后加上NULL作為字符串結束。所讀取的字符串暫存在給定的參數string中。
【返回值】若成功則返回string的指針,否則返回NULL。
注意:由於gets()不檢查字符串string的大小,必須遇到換行符或文件結尾才會結束輸入,因此容易造成緩存溢出的安全性問題,導致程序崩潰,可以使用fgets()代替。
【實例】請看下面一個簡單的例子。
- #include <stdio.h>
- int main(void)
- {
- char str[10];
- printf("Input a string.\n");
- gets(str);
- printf("The string you input is: %s",str); //輸出所有的值,注意a
- }
如果輸入123456(長度小於10),則輸出結果為:
Input a string.
123456↙
The string you input is:123456
如果輸入12345678901234567890(長度大於10),則輸出結果為:
Input a string.
12345678901234567890↙
The string you input is:12345678901234567890
同時看到系統提示程序已經崩潰。
如果不能正確使用gets()函數,帶來的危害是很大的,就如上面我們看到的,輸入字符串的長度大於緩沖區長度時,並沒有截斷,原樣輸出了讀入的字符串,造成程序崩潰。
考慮到程序安全性和健壯性,建議用fgets()來代替gets()。
如果你在GCC中使用gets(),編譯無法通過,會提示:
the 'gets' function is dangerous and shout not be used.