您的位置:首页 > 编程语言 > C语言/C++

个人记事本

2016-07-08 20:16 211 查看
strlen

fgets
综合以上两点一个典型的例子从键盘读如一串字符然后求其大小长度

我们再把程序修改一下验证缓冲的存在

1.strlen()

size_t strlen(const char *s);


The strlen() function calculates the length of the string s, excluding**(不包括)** the terminating null byte (‘\0’).

计算长度时,不包括末尾的结束符’\0’

但是,换行符’\n’要计算在内

2. fgets()

char *fgets(char *buff, int size, FILE *stream);


man手册:

fgets() reads in at most one less than size characters from stream

and stores them into the buffer pointed to by s. Reading stops after an

EOF or a newline. If a newline is read, it is stored into the buffer.

A terminating null byte (‘\0’) is stored after the last character in the buffer.

将文件流中的size个字符保存到char *s中;

直到读到文件的结尾EOF或者是读到新的一行结束(即读到换行符’\n’结束,当然也会把’\n’读到s中)。

然后会在buffer的最后一个字符后自动添加一个’\0’。

如果,读入的一行小于buffer的缓冲区大小BUFFSIZE,则会在’\n’后’\0’,最后形成的效果就是

char buff[BUFFSIZE] = {'h', 'e', 'l', 'l', 'o', '\n', '\0'};


如果,读入的一行大于了buff的缓冲区大小BUFFSIZE,那么buff中的最后一位会用’\0’占位,其余的多余会存放在缓冲区中(当下次再调用fgets时,变回取出),也就是说实际get到的只有BUFFSIZE-1个字符。

综合以上两点,一个典型的例子:从键盘读如一串字符,然后求其大小长度。

char buf[5];
fgets(buf, sizeof(buf), stdin);
printf("buf= %s", buf);
printf("strlen(buf)= %d.", strlen(buf));


如果从键盘输入:

xxxx5xxx<CR>


那么执行结果为:

buf= xxxxstrlen(buf)= 4
//注意,这里没有换行哦,因为fgets截断了stdin,只取了前四个x,最后一位用结束符'\0'补齐,而strlen不把结束符计算在内,因此为4.


我们再把程序修改一下:验证缓冲的存在

char buf[5];

while(fgets(buf, sizeof(buf), stdin))
{
printf("sizeofbuf = %d\n",sizeof(buf));
printf("buf = %s", buf);
printf("strlen(buf)= %d.\n", strlen(buf));
printf("--------------------\n");
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言