文字解释:
char *s_gets(char *st, int n)
是为了获取字符st中的n个元素,并将其结果返回为s_gets的字符指针。功能类似于fgets函数,但它解决了fgets函数会读取'\n'
的问题。
回顾fgets函数:
fgets函数原型
#include <stdio.h>
...
char *fgets(char *s, int size, FILE *stream);
s-字符型指针,用于存放字符串的位置
int size-指定读取字符的数量
stream-用于读取字符串的文件流
返回值:
-
如果函数调用成功,返回 s 参数指向的地址。
-
如果在读取字符的过程中遇到 EOF(END OF FILE),即 eof 指示器被设置;如果还没读入任何字符就遇到这种 EOF,则 s 参数指向的位置保持原来的内容,函数返回 NULL。
-
如果在读取的过程中发生错误,则 error 指示器被设置,函数返回 NULL,但 s 参数指向的内容可能被改变。
s_gets函数测试案例
附上代码测试用例帮助你更好的理解
PS:
main函数 n 取 10,实际上只能读取n-1也就是9个字符
为了更好的理解,你也可以自行设置n的大小(-1,0等等)
代码上有比较详细的注释,先将代码拷贝到编译器能帮助你更好地理解
#include<stdio.h>
#include<string.h>
char *s_gets(char *st, int n);
char *s_gets(char *st, int n)
{
char *ret_val;
char * find;
ret_val = fgets(st,n,stdin); //表示从标准输入流中读取n-1个元素到字符st中,再将指针ret_val指向指针st
if(ret_val) //if语句为了避免fgets函数返回值为NULL的情况
{
find = strchr(st,'\n');
if(find) //核心点:将\n转化成\0
{
*find = '\0';
}
else
{
while(getchar() != '\n') //清除IO缓冲区
continue;
}
}
return ret_val;
}
int main()
{
char s[40];
int n = 10;
printf("%s\n",s_gets(s,n));
return 0;
}