C中包含\0的字符串的长度
我把用户的输入读作:C中包含\0的字符串的长度,c,input,strlen,C,Input,Strlen,我把用户的输入读作: scanf("%[^\n]", message); 我初始化char message[100]=“”现在,在另一个函数中,我需要找出消息中输入的长度,我使用strlen()很容易就做到了,不幸的是,当我稍后在终端中这样做时,它不能正常工作 echo -e "he\0llo" | .asciiart 50 它将读取整个输入,但strlen仅返回长度2 有没有其他方法可以确定输入的长度?根据定义,strlen在空字符上停止 在读取字符串后,必须计算/读取到EOF和/或换
scanf("%[^\n]", message);
我初始化char message[100]=“”代码>现在,在另一个函数中,我需要找出消息中输入的长度,我使用strlen()
很容易就做到了,不幸的是,当我稍后在终端中这样做时,它不能正常工作
echo -e "he\0llo" | .asciiart 50
它将读取整个输入,但strlen
仅返回长度2
有没有其他方法可以确定输入的长度?根据定义,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");
}
正如您所见,无法区分空行和EOF(即使查看errno)
您还可以使用ssize\u t getline(char**lineptr,size\u 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);
}
strlen()
在字符数组中搜索第一个出现的\0
,因此无法搜索包含\0
字符的任意数组。@chux你说得很对,谢谢你的评论,我编辑了我的答案(我很惊讶我没有将限制设置为99个字符,我总是设置限制并告诉其他人这样做^^)
#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