C11新增的gets_s(),比fgets()少了第3个参数
示例
//Visual Studio中加上这句才可以使用scanf()
//否则只能使用scanf_s()
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdbool.h>
#define STLEN 10
char * s_gets(char * st, int n);
//argc: 参数个数 argv[]: 参数数组
int main(int argc, char *argv[])
{
char words[STLEN];
puts("Enter a string:");
//C11新增的gets_s(),比fgets()少了第3个参数
/*
1. gets_s()只从标准输入中读取数据,所以不需要第3个参数。
2. 如果gets_s()读到换行符,会丢弃它而不是储存它。
3. 如果gets_s()读到最大字符数都没有读到换行符,会执行以下几步。
首先把目标数组中的首字符设置为空字符,读取并丢弃随后的输入直至
读到换行符或文件结尾,然后返回空指针。接着,调用依赖实现的“处理函数”
(或你选择的其他函数),可能会中止或退出程序。
*/
//当输入字符越过STLEN-1时,会导致程序报错。
gets_s(words, STLEN);
puts(words);
system("pause");
return 0;
}
// 自己实现读取函数
char * s_gets(char * st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val) //即,ret_val != NULL
{
while (st[i] != '\n' && st[i] != '\0')
i++;
if (st[i] == '\n')
st[i] = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
运行测试