根据定义 strlen 在空字符处停止
您必须在读取字符串后计数/读取到 EOF 和/或换行符,而不是计数到空字符
正如%n 的评论中所说,允许获取读取的字符数,例如:
#include <stdio.h>
int main()
{
char message[100] = { 0 };
int n;
if (scanf("%99[^\n]%n", message, &n) == 1)
printf("%d\n", n);
else
puts("empty line or EOF");
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -g c.c
pi@raspberrypi:/tmp $ echo "" | ./a.out
empty line or EOF
pi@raspberrypi:/tmp $ echo -n "" | ./a.out
empty line or EOF
pi@raspberrypi:/tmp $ echo -e "he\0llo" | ./a.out
6
pi@raspberrypi:/tmp $
如您所见,无法区分空行和 EOF(即使查看 errno)
你也可以使用ssize_t getline(char **lineptr, size_t *n, FILE *stream);:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *lineptr = NULL;
size_t n = 0;
ssize_t sz = getline(&lineptr, &n, stdin);
printf("%zd\n", sz);
free(lineptr);
}
但在这种情况下,可能的换行符会被获取并计数:
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -g c.c
pi@raspberrypi:/tmp $ echo -e "he\0llo" | ./a.out
7
pi@raspberrypi:/tmp $ echo -e -n "he\0llo" | ./a.out
6
pi@raspberrypi:/tmp $ echo "" | ./a.out
1
pi@raspberrypi:/tmp $ echo -n "" | ./a.out
-1