C中带\ 0的字符串的长度 [英] Length of string with \0 in it in C
问题描述
我将用户的输入读为:
scanf("%[^\n]", message);
现在我初始化char消息[100] ="";
,在另一个函数中我需要找出消息中输入的长度,我很容易用strlen()
做到了这一点,不幸的是,当我稍后在终端<中执行此操作时,它无法正常工作/p>
And I initialise char message [100] ="";
now, in another function I need to find out length of input in message, I did it easily with strlen()
, unfortunately it doesn't work correctly when I do later in terminal
echo -e "he\0llo" | .asciiart 50
它将读取整个输入,但strlen
仅返回长度2.
It will read the whole input BUT strlen
will only return length 2.
还有其他方法可以找出输入的长度吗?
Is there any other way I could find out length of input ?
推荐答案
按定义
在读取字符串后,您必须计数/最多读取EOF和/或换行符,而不是最多计数空字符
you have to count/read up to EOF and/or the newline rather than counting up to the null character after you read the string
如前所述,%n
允许获取读取的字符数,例如:
As said in a remark %n
allows to get the number of read characters, example :
#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 )
As you can see it is not possible to distinguish an empty line and EOF (even looking at 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);
}
但在这种情况下,可能的换行符已获取并计数:
but the possible newline is get and counted in that case :
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
这篇关于C中带\ 0的字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!