C语言中带\0的字符串长度
Length of string with \0 in it in C
好吧,我从用户那里读到的输入是:
scanf("%[^\n]", message);
我现在初始化字符消息 [100] ="";
,在另一个函数中我需要找出消息中输入的长度,我用 strlen()
轻松做到了,不幸的是当我稍后在终端
echo -e "he[=11=]llo" | .asciiart 50
它将读取整个输入,但 strlen
只会读取 return 长度 2。
有没有其他方法可以找出输入的长度?
根据定义 strlen 在空字符处停止
你必须 count/read 直到 EOF and/or 换行符,而不是在你读取字符串后计数到空字符
如备注所述 %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[=11=]llo" | ./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[=13=]llo" | ./a.out
7
pi@raspberrypi:/tmp $ echo -e -n "he[=13=]llo" | ./a.out
6
pi@raspberrypi:/tmp $ echo "" | ./a.out
1
pi@raspberrypi:/tmp $ echo -n "" | ./a.out
-1
好吧,我从用户那里读到的输入是:
scanf("%[^\n]", message);
我现在初始化字符消息 [100] ="";
,在另一个函数中我需要找出消息中输入的长度,我用 strlen()
轻松做到了,不幸的是当我稍后在终端
echo -e "he[=11=]llo" | .asciiart 50
它将读取整个输入,但 strlen
只会读取 return 长度 2。
有没有其他方法可以找出输入的长度?
根据定义 strlen 在空字符处停止
你必须 count/read 直到 EOF and/or 换行符,而不是在你读取字符串后计数到空字符
如备注所述 %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[=11=]llo" | ./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[=13=]llo" | ./a.out
7
pi@raspberrypi:/tmp $ echo -e -n "he[=13=]llo" | ./a.out
6
pi@raspberrypi:/tmp $ echo "" | ./a.out
1
pi@raspberrypi:/tmp $ echo -n "" | ./a.out
-1