1 函数原型
gets():从标准输入流stdin中读取字符串,函数原型如下:
char * gets ( char * str );
cstdio库描述如下:
Get string from stdin
1. Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached.
2. The newline character, if found, is not copied into str.
3. A terminating null character is automatically appended after the characters copied to str.
4. Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows).
2 参数
gets()函数只有一个参数str:
- 参数str是一个指向字符数组的指针,类型为char*;str指向的字符数组用于存储从标准输入流stdin读取的字符串。
cstdio库描述如下:
str
1. Pointer to a block of memory (array of char) where the string read is copied as a C string.
3 返回值
gets()函数的返回值类型为char*型:
- 读取成功,返回str;
- 读取失败,返回NULL。
cstdio库描述如下:
1. On success, the function returns str.
2. If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged).
3. If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
4 读取机制
gets()函数从标准输入流stdin中读取字符,直至遇到换行符’\n’:
- 将换行符‘\n’之前的所有字符依次存入str指向的字符数组中;
- 当读到换行符‘\n’时,将换行符‘\n’丢弃,并在字符串末尾添加空字符’\0’,作为字符串结束符。
注意事项:
- 如果从标准输入流stdin中读取的第一个字符就是换行符’\n’,则str指向的字符数组中存储的是个空字符串,即只包含空字符’\0’的字符串;
- gets()函数存在一个重大缺陷:gets()函数会读空标准输入流stdin,因此无法预知读取的字符串的长度;gets()函数不检查str指向的字符数组是否能够容纳读取的字符串,因此存在内存访问越界的隐患。
5 示例
示例代码如下所示:
void clear_stdin(void)
{
//
while (getchar() != '\n');
//
return;
}
int main()
{
//定义变量
char str[80] = { 0 };
char ch = 0;
//输入字符串:2个空格+abc+Tab+def+2个空格回车
gets(str);
//输出字符串
puts(str);
//输出字符串长度
printf("%d\n", strlen(str));
//检查stdin是否为空,若为空则输入字符'c'并打印
ch = getchar();
clear_stdin();
putchar(ch);
//
printf("\n");
//
return 0;
}
代码运行结果如下图所示:
代码及运行结果分析如下:
- gets()函数读取了标准输入流stdin中回车符’\n’之前的所有字符,即4个空格+6个英文字母+1个制表符=11个字符,与strlen统计结果相符;
- 在调用gets()函数之后,再次调用getchar()函数,控制台提示用户输入字符,说明gets()函数已将标准输入流stdin读空(包括换行符‘\n’)。