简体   繁体   English

C中带\\ 0的字符串的长度

[英]Length of string with \0 in it in C

Well I read input from user as: 好吧,我从用户那里读取了输入:

scanf("%[^\n]", message); 

And I initialise char message [100] =""; 我初始化char消息[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 现在,在另一个函数中,我需要找出消息中输入的长度,我很容易用strlen() ,不幸的是,当我稍后在终端中执行时,它无法正常工作

echo -e "he\0llo" | .asciiart 50 

It will read the whole input BUT strlen will only return length 2. 它将读取整个输入,但strlen只会返回长度2。

Is there any other way I could find out length of input ? 有没有其他方法可以找出输入的长度?

By definition strlen stops on the null character 根据定义, strlen停在空字符上

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 您必须计算/读取EOF和/或换行符,而不是在读取字符串后计算到空字符

As said in a remark %n allows to get the number of read characters, example : 正如在注释中所述, %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");
}

Compilations and executions : 编译和执行:

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 $ 

As you can see it is not possible to distinguish an empty line and EOF (even looking at errno ) 正如你所看到的那样,无法区分空行和EOF(甚至看着errno

You can also use ssize_t getline(char **lineptr, size_t *n, FILE *stream); 您也可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM