[英]Length of string with \0 in it in C
好吧,我從用戶那里讀取了輸入:
scanf("%[^\n]", message);
我初始化char消息[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");
}
編譯和執行:
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 )
您也可以使用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\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.