C语言中的fgets()和gets()

要读取带空格的字符串值,我们可以在C编程语言中使用get()或fgets()。在这里,我们将看到get()和fgets()之间的区别。

null

fgets()

它从指定的流中读取一行,并将其存储到str指向的字符串中。当读取(n-1)个字符、读取换行符或到达文件末尾时(以先到者为准),它停止。 语法:

char *fgets(char *str, int n, FILE *stream)
str : Pointer to an array of chars where the string read is copied.
n : Maximum number of characters to be copied into str 
(including the terminating null-character).
*stream : Pointer to a FILE object that identifies an input stream.
stdin can be used as argument to read from the standard input.

returns : the function returns str
  • 它遵循一些参数,如最大长度、缓冲区、输入设备参考。
  • 它是 安全 使用,因为它检查数组绑定。
  • 它会一直读取,直到遇到新行字符或字符数组的最大限制。

例如:假设最大字符数为15,输入长度大于15,但fgets()仍将只读取15个字符并打印。

// C program to illustrate
// fgets()
#include <stdio.h>
#define MAX 15
int main()
{
char buf[MAX];
fgets (buf, MAX, stdin);
printf ( "string is: %s" , buf);
return 0;
}


因为fgets()读取用户的输入,所以我们需要在运行时提供输入。

Input:
Hello and welcome to GeeksforGeeks

Output:
Hello and welc

获取()

从标准输入(stdin)中读取字符,并将其作为C字符串存储到str中,直到到达换行符或文件结尾。 语法:

char * gets ( char * str );
str :Pointer to a block of memory (array of char) 
where the string read is copied as a C string.
returns : the function returns str
 
  • 使用它不安全,因为它不检查数组绑定。
  • 它用于从用户处读取字符串,直到没有遇到换行符为止。

示例:假设我们有一个由15个字符组成的字符数组,并且输入大于15个字符,gets()将读取所有这些字符并将它们存储到变量中。由于gets()不检查输入字符的最大限制,因此编译器随时可能返回缓冲区溢出错误。

// C program to illustrate
// gets()
#include <stdio.h>
#define MAX 15
int main()
{
char buf[MAX];
printf ( "Enter a string: " );
gets (buf);
printf ( "string is: %s" , buf);
return 0;
}


由于gets()读取用户的输入,所以我们需要在运行时提供输入。

Input:
Hello and welcome to GeeksforGeeks

Output:
Hello and welcome to GeeksforGeeks
© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享