通常,strlen()不计算字符串末尾的空终止符.但是,下面的代码使用null终止符打印字符串计数.谁能解释我为什么?谢谢
char str2[100];
printf("\nEnter a string: ");
fgets (str2, sizeof(str2), stdin);
printf("\n%d",strlen(str2));
Run Code Online (Sandbox Code Playgroud)
小智 45
我假设前面的fgets提示拾取了newline角色.
例如:
你把apple.
在内部,您的字符串存储为apple\n\0.
strlen然后返回6为apple+'\n'
fgets()当遇到换行符(使用时输入键)时,该函数接受输入stdin,并且换行符\n被该函数视为有效字符,并包含在复制到您的字符串中 str2。因此,当您将其作为参数传递给它时,strlen()它会给出比字符串中的原始字符数多 1 个字符以表示附加\n字符。
如果您想要原始字符数或不想\n添加 a,请使用该gets()函数,因为它不会复制换行符。而且,您只需要传递字符串作为参数,无需传递流( stdin) 作为默认流gets()是stdin。
char str2[100];
printf("\nEnter a string: ");
gets(str2);
printf("\n%d",strlen(str2));
Run Code Online (Sandbox Code Playgroud)