#include <stdio.h>
#include <string.h>
char* s_gets(char* dest, int n)
{
char* ret_val = NULL;
int i = 0;
ret_val = fgets(dest, n, stdin);
if (ret_val)
{
while (dest[i] != '\n' && dest[i] != '\0')
i++;
if (dest[i] == '\n')
{
dest[i] = '\0';
}
else
{
while (getchar() != '\n')
continue;
}
}
return s_gets
}
dest:字符串存储地址
n:读入字符最大数量, 实际字符长度应为n - 1。 末尾1位空字符'\0'。
内部调用fgets, 顺序读取字符串, 直到读取到换行符或空字符'\0'。
if 读到换行符,替换成空字符'\0'。
if 读到空字符, 舍弃剩下的字符。getchar只读取,不存储,知道读到换行符。
本文详细解析了C语言中自定义的s_gets函数,该函数用于从标准输入读取字符串,直至遇到换行符或文件结束符,并进行必要的字符处理。文章深入探讨了函数的实现细节,包括如何避免读入多余的换行符,以及如何确保字符串以空字符结尾。
1442

被折叠的 条评论
为什么被折叠?



