【C语法学习】6 - gets()函数

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:

  1. 参数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类型的指针:

  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. 接受换行符之前的所有字符,包括空格、制表符等字符;
  2. 将换行符’\n’替换为空字符’\0’,作为字符串结束符;
  3. 将字符串储存在str指向的内存空间里。

注意事项

  1. 如果从标准输入流stdin中读取的第一个字符就是换行符’\n’,则str指向的字符串是个空字符串,即只包含空字符’\0’的字符串;
  2. 在调用gets()函数之前,必须分配足够的内存空间来储存str指向的字符串;
  3. 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;
}

运行结果如下图所示:

在这里插入图片描述

分析程序及运行结果:

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值