有人可以告诉我这是什么意思吗:"%.*s"
例如,它在这里使用:
sprintf(outv->deliveryAddressCity,
"%.*s",
sizeof(outv->deliveryAddressCity)-1,
mi->deliveryAddressCity);
有人可以告诉我这是什么意思吗:"%.*s"
例如,它在这里使用:
sprintf(outv->deliveryAddressCity,
"%.*s",
sizeof(outv->deliveryAddressCity)-1,
mi->deliveryAddressCity);
%.*s
是指从以下缓冲区打印前 X 个字符。在这种情况下,从 mi->deliveryAddressCity
中打印出第一个 sizeof(outv->deliveryAddressCity) - 1
个字符,以防止超出 outv->deliveryAddressCity
的范围。
一个更短的例子:
printf("%.*s", 4, "hello world");
将会打印出hell
。
printf("%.*s", 3, "abcdef");
打印 "abc"。
.*
精度没有在格式字符串中指定,而是作为一个额外的整数值参数出现在要格式化的参数之前。
因此,在您的情况下,字符串的大小为sizeof(outv->deliveryAddressCity )-1
当您拥有一个没有以空字符结尾的字符串,并且长度存储在其他地方时,它通常用于最常见的情况。
例如:
{
char* regular_string = "Hello World"; // This string has a null-Terminator.
char untermed_string[11];
int len;
// Specifically make untermed string so it is NOT null-terminated.
memcpy(untermed_string, regular_string, 11);
len = 11;
printf("The string is %.*s\n", len, untermed_string); // This will still print the proper data!
printf("The start of the string is %.*s\n", 5, untermed_string); // This will only print "Hello".
}
这是一个格式说明符,它从堆栈中取出2个值,第一个是大小,第二个是值。
.-表示法:至少长度.最大长度(所以".*"表示:最多*个字符)
它可以帮助您打印字符串的一部分。您可以指定要打印字符串的长度。例如:printf("%.*s", 5, "rahul subedi"),输出结果为:rahul。