Length of string with \0 in it in C

2019-08-17 17:03发布

Well I read input from user as:

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

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 

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 ?

标签: c input strlen
1条回答
疯言疯语
2楼-- · 2019-08-17 17:50

By definition strlen stops on the null character

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

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");
}

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)

You can also use 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
查看更多
登录 后发表回答