printf中"%.*s"是什么意思?

3

有人可以告诉我这是什么意思吗:"%.*s"

例如,它在这里使用:

  sprintf(outv->deliveryAddressCity, 
          "%.*s",
          sizeof(outv->deliveryAddressCity)-1,
          mi->deliveryAddressCity);

3
http://www.cplusplus.com/reference/cstdio/printf/ - djechlin
我冒昧地编辑了代码,并将sprintf的参数放在不同的行上,因为原始代码难以阅读。 - Lundin
请返回翻译文本:and your duplicate - https://dev59.com/c1XTa4cB1Zd3GeqPzDDn - djechlin
感谢指出重复项,那个字符串对于谷歌来说很难搜索。 - Malfist
7个回答

8

%.*s 是指从以下缓冲区打印前 X 个字符。在这种情况下,从 mi->deliveryAddressCity 中打印出第一个 sizeof(outv->deliveryAddressCity) - 1 个字符,以防止超出 outv->deliveryAddressCity 的范围。

一个更短的例子:

printf("%.*s", 4, "hello world");

将会打印出hell


2
也许通过以下示例,您可以更好地理解它:
printf("%.*s", 3, "abcdef");

打印 "abc"。


2

1
“宽度”和“精度”格式参数可被省略,或者它们可以作为嵌入在格式字符串中的固定数字,或者当格式字符串中有星号“*”时,作为另一个函数参数传递。例如,printf("%*d", 5, 10)将结果打印为“ 10”,总宽度为5个字符;printf("%.*s", 3, "abcdef")将结果打印为“abc”。(这真的很容易在搜索引擎上找到...)”

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".
}

例如,在混合使用C和Fortran时,它会使用空格填充而不是以null结尾(令人讨厌)。 - djechlin

0

这是一个格式说明符,它从堆栈中取出2个值,第一个是大小,第二个是值。

.-表示法:至少长度.最大长度(所以".*"表示:最多*个字符)


0

它可以帮助您打印字符串的一部分。您可以指定要打印字符串的长度。例如:printf("%.*s", 5, "rahul subedi"),输出结果为:rahul。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接