2010-05-28 176 views
2

編譯Ubuntu的業報一些遺留的C代碼時,我得到以下警告,使用gcc 4.4.1警告:「0」標誌忽略精度和「%」我格式gnu_printf

的警告是:

SRC/FILENAME.C:385:警告: '0' 標誌 忽略精度和 '%我' gnu_printf格式

這將導致警告將被髮射的代碼段是:

char  buffer[256] ; 
long  fnum ; 
/* some initialization code here ... */ 
sprintf(buffer, "F%03.3i.DTA", (int)fnum); /* <- warning emitted here */ 

我想我明白了警告,但我想您在這裏看到,如果我是正確的,也是(定)正確解決這種方式。

+0

你的理解是什麼?解決它的正確方法顯然是消除零。 – 2010-05-28 08:14:56

+0

我的理解是數據類型和格式說明符之間存在不兼容性(這很可能是由於試圖用精度格式化整數值)。 – morpheous 2010-05-28 08:18:30

+0

不,對於整型說明符有一個精度是有效的。如手冊頁所述,它用於提供用於格式化的最小位數。 – 2010-05-28 08:23:15

回答

3

printf(3)手冊頁:

0  The value should be zero padded. For d, i, o, u, x, X, a, A, e, 
      E, f, F, g, and G conversions, the converted value is padded on 
      the left with zeros rather than blanks. If the 0 and - flags 
      both appear, the 0 flag is ignored. If a precision is given 
      with a numeric conversion (d, i, o, u, x, and X), the 0 flag is 
      ignored. For other conversions, the behavior is undefined. 

所以,你可以有一個零填充或數字的最小數目,但不能同時使用。

+0

沒什麼可說的。 RTFM。 – Clifford 2010-05-28 08:47:22

+0

對不起,但是......如果我們沒有獨立於值的長度表示字段的長度,我們將如何填充零值? – PypeBros 2010-12-16 14:54:00

+0

@sylvanulg:指定精度會導致'printf()'填充'0'來填充該長度。只要確保精度大於或等於字段寬度。 – 2010-12-16 14:58:38