6 - gets()函数

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:

  1. 参数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*型:

  1. 读取成功,返回str;
  2. 读取失败,返回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’:

  1. 将换行符‘\n’之前的所有字符依次存入str指向的字符数组中;
  2. 当读到换行符‘\n’时,将换行符‘\n’丢弃,并在字符串末尾添加空字符’\0’,作为字符串结束符。

注意事项

  1. 如果从标准输入流stdin中读取的第一个字符就是换行符’\n’,则str指向的字符数组中存储的是个空字符串,即只包含空字符’\0’的字符串;
  2. 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;
}

代码运行结果如下图所示:

在这里插入图片描述

代码及运行结果分析如下:

  1. gets()函数读取了标准输入流stdin中回车符’\n’之前的所有字符,即4个空格+6个英文字母+1个制表符=11个字符,与strlen统计结果相符;
  2. 在调用gets()函数之后,再次调用getchar()函数,控制台提示用户输入字符,说明gets()函数已将标准输入流stdin读空(包括换行符‘\n’)。
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值