当前位置: C语言 -- 标准库 -- <stdio.h> -- gets

gets函数


概要:

#include <stdio.h>

char *gets(char *s);


描述:

该函数从标准输入流中读取字符到参数s指向的数组,直至文件末尾或者遇到换行符。换行符会被丢弃,并在读取最后一个字符后向数组中添加空字符。

ISO/IEC 9899:2018标准已删除此函数,但定义了该函数的安全版本gets_s


参数:
char *s

char类型指针,读取的字符将存储在其指向的数组中。


返回值:

如果调用成功,函数返回s

如果到达文件末尾并且没有读取任何字符到数组中,函数返回空指针,并且数组内容保持不变。

如果发生读取错误,函数返回空指针,并且数组内容是不确定的。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
/*函数gets范例*/

#include <stdio.h>

#define LENGTH 100

int main(void)
{
    char str[LENGTH];

    puts("Input a sentence:");
    gets(str);
    puts(str);

    return 0;
}


结果:

假设输入内容为:

If you do not learn to think when you are young, you may never learn. -Edison

将输出:

If you do not learn to think when you are young, you may never learn. -Edison


相关内容:
fgets 从输入流读取字符串的函数。