簡體   English   中英

%*s 格式說明符是什么意思?

[英]What does the %*s format specifier mean?

在我必須維護的一些代碼中,我看到了格式說明符%*s 誰能告訴我這是什么以及為什么使用它?

它的用法示例如下:

fprintf(outFile, "\n%*s", indent, "");

它用於以動態方式指定字段的寬度

  • 寬度未在格式字符串中指定,而是作為必須格式化的參數之前的附加 integer 值參數指定。

所以“縮進”指定在參數列表中為它后面的字符串分配多少空間。

所以,

printf("%*s", 5, "");

是相同的

printf("%5s", "");

這是在文件中放置一些空格以避免循環的好方法。

不要在不是 NULL 終止(打包)的緩沖區上使用“%*s”,認為它只會打印“長度”字段。

格式說明符 %4s 輸出字段寬度為 4 的字符串,即 printf 顯示具有至少 4 個字符位置的值。

如果 output 的值less 4 個字符位置寬,默認情況下該值在字段中right justified

如果該值greater 4 個字符位置寬,則字段寬度expands以容納適當的字符數。

要左對齊該值,請使用負值 integer 指定字段寬度。

參考資料: Java™ 如何編程(早期對象),第十版

在 printf 和 fprintf 中使用時:

printf("%*s", 4, myValue); is equivalent to printf("%4s", myValue);

它顯示具有最小寬度的變量,rest 個右對齊空格。 要左對齊該值,請使用負數 integer。

在 scanf 和 sscanf 中使用時:

/* sscanf example */
#include <stdio.h>

int main ()
{
  char sentence []="Rudolph is 12 years old";
  char str [20];
  int i;

  sscanf (sentence,"%s %*s %d",str,&i);
  printf ("%s -> %d\n",str,i);
  
  return 0;
}

Output:

Rudolph -> 12

它用於忽略字符串。

* 使 fprintf 填充 output 直到它有 n 個字符寬,其中 n 是存儲在 function 參數中的 integer 值,就在修改后的類型所代表的參數之前。

printf("%*d", 5, 10) //will result in "10" being printed with a width of 5.

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

寬度未在格式字符串中指定,而是作為必須格式化的參數之前的附加 integer 值參數指定。

例如: printf("%*s", 4, myValue); 等同於printf("%4s", myValue); .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM