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()
函数,以便从通常是终端的标准输入中读取输入。 gets
是get 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);
}
![](https://img-blog.csdnimg.cn/img_convert/9c09ee5941f50130c0914ce4d2682f7b.png)
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 morescanf()是标准的C函数,但是gets不再
- scanf() end taking input upon encountering whitespace, newline or EOF but gets end taking input upon encountering newline and EOFscanf()在遇到空格,换行符或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()
提供了更安全的方式来读取标准输入。
翻译自: https://www.poftut.com/c-programming-gets-function-tutorial-with-examples/