這裏的字符串長度是一個例子:
#include <stdio.h>
#include <string.h>
#define MAX_DIGITS 5
int
main()
{
char buf[80];
char *s = NULL;
printf ("\n>>Enter string, %d digits or less: ", MAX_DIGITS);
s = fgets (buf, MAX_DIGITS+1, stdin);
printf ("strlen(buf)=%d, buf=%s, strlen(s)=%d, s=%s\n",
strlen(buf), buf, strlen(s), s);
return 0;
}
輸出樣本,以「MAX_DIGITS」和「MAX_DIGITS + 1 「:
>>Enter string, 5 digits or less: 1
strlen(buf)=2, buf=1
, strlen(s)=2, s=1
.
>>Enter string, 5 digits or less: 12
strlen(buf)=3, buf=12
, strlen(s)=3, s=12
.
>>Enter string, 5 digits or less: 123
strlen(buf)=4, buf=123
, strlen(s)=4, s=123
.
>>Enter string, 5 digits or less: 1234
strlen(buf)=5, buf=1234
, strlen(s)=5, s=1234
.
>>Enter string, 5 digits or less: 12345
strlen(buf)=5, buf=12345, strlen(s)=5, s=12345.
>>Enter string, 5 digits or less: 123456
strlen(buf)=5, buf=12345, strlen(s)=5, s=12345.
你會發現:
的返回b只要#/位是< MAX_DIGITS,uffer就會保留「\ n」。
當#/ digits> = MAX_DIGITS時,「\ n」被刪除。
你的緩衝區必須容納MAX_DIGITS + 1
的printf( 「LEN:%d」,LEN); printf(「str:%s」,str); \t printf(「hi」); return 0; }添加少量印刷有助於澄清下面給出的答案。注意如何打印「hi」。 – kumar