带有示例的C编程Gets()函数教程

C and C++ programming language provide the functiongets() in order to read input from standard input which is generally a terminal. gets is the short form of the get string where string shortens as s . In this tutorial, we will learn functiongets() usage with different examples and compare with functionscanf().

C和C ++编程语言提供了gets()函数,以便从通常是终端的标准输入中读取输入。 getsget string的缩写形式,其中string缩短为s 。 在本教程中,我们将通过不同的示例学习函数gets()用法,并与函数scanf()进行比较。

宣言 (Declaration)

The functiongets() has the following syntax which only accepts string parameter.

函数gets()具有以下语法,该语法仅接受字符串参数。

char *gets(char *str)
  • *str is a pointer to a string variable where string read from standard input will be put.

    *str是指向字符串变量的指针,将从标准输入中读取的字符串放入该变量中。

返回值 (Return Value)

The return value of the functiongets() is also the string read from standard input. If there is an error willNULL be returned which means no character read.

函数gets()的返回值也是从标准输入读取的字符串。 如果有错误,将返回NULL ,这意味着未读取任何字符。

(Example)

In this example, we will get the name from standard input and put into char array or string str then print with printf() function.

在此示例中,我们将从标准输入中获取名称,并将其放入char数组或字符串str然后使用printf()函数进行打印。

#include <stdio.h> 

int main () { 
  char str[50]; 

  printf("Enter a your name : "); 
  gets(str); 

  printf("Hello  %s", str); 

  return(0); 
}

gets()vs scanf() (gets() vs scanf())

In this part, we will compare and find similarities and differences between gets() and scanf()

在这一部分中,我们将比较并发现gets()scanf()之间的相似之处和不同之处

  • scanf() is a standard C function but gets is not any more

    scanf()是标准的C函数,但是gets不再
  • scanf() end taking input upon encountering whitespace, newline or EOF but gets end taking input upon encountering newline and EOF

    scanf()在遇到空格,换行符或EOF时结束输入,但在遇到换行符和EOF时结束输入

使用安全的fgets()函数(Using Secure fgets() Function)

gets() function is open to a buffer overflow which is a security vulnerability. So functionfgets() provides more secure way to read from standard input.

gets()函数对缓冲区溢出开放,这是一个安全漏洞。 因此,函数fgets()提供了更安全的方式来读取标准输入。

LEARN MORE  C fgets() Function Usage Examples To Read File
了解更多C fgets()函数读取文件的用法示例

翻译自: https://www.poftut.com/c-programming-gets-function-tutorial-with-examples/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值