1 函数原型
gets():从标准输入流stdin读取一个字符串存储到str指向的内存空间,函数原型如下:
char *gets(char *str)
cstdio库描述如下:
1. Get string from stdin.
2. 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.
3. The newline character, if found, is not copied into str.
4. A terminating null character is automatically appended after the characters copied to str.
5. 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可以是一个字符指针变量名,也可以是一个字符数组名。
cstdio库描述如下:
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’替换为空字符’\0’,作为字符串结束符;
- 将字符串储存在str指向的内存空间里。
注意事项:
- 如果从标准输入流stdin中读取的第一个字符就是换行符’\n’,则str指向的字符串是个空字符串,即只包含空字符’\0’的字符串;
- 在调用gets()函数之前,必须分配足够的内存空间来储存str指向的字符串;
- gets()函数存在一个重大缺陷:gets()函数会读空标准输入流stdin,因此无法预知从标准输入流stdin中读取的字符串的长度;gets()函数不检查str指向的内存空间是否能够容纳从标准输入流stdin中读取的字符串,因此存在内存访问越界的隐患。
5 示例
示例代码如下所示:
void clear_stdin(void)
{
while (getchar() != '\n');
}
int main()
{
//定义变量
char str[80] = { 0 };
char ch;
//输入字符串: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中读空(包括换行符)。