2009-09-25 46 views
4

所以,我有點困難。根據我的系統中的man 3 printf,字符串格式"%5s"應該使用指定的精度來限制從給定的字符串參數打印的字符數。printf似乎忽略了字符串精度

 
% man 3 printf 
PRINTF(3)    BSD Library Functions Manual    PRINTF(3) 

NAME 
    printf, fprintf, sprintf, snprintf, asprintf, vprintf, vfprintf, 
    vsprintf, vsnprintf, vasprintf -- formatted output conversion 

... 
    s  The char * argument is expected to be a pointer to an array of 
      character type (pointer to a string). Characters from the array 
      are written up to (but not including) a terminating NUL charac- 
      ter; if a precision is specified, no more than the number    
      specified are written. If a precision is given, no null 
      character need be present; if the precision is not specified, or 
      is greater than the size of the array, the array must contain a 
      terminating NUL character. 

但我的測試代碼並不確認這一點:

#include <stdio.h> 
int main() 
{ 
     char const * test = "one two three four"; 
     printf("test: %3s\n", test); 
     printf("test: %3s\n", test+4); 
     printf("test: %5s\n", test+8); 
     printf("test: %4s\n", test+14); 
     return 0; 
} 

它輸出

 
test: one two three four 
test: two three four 
test: three four 
test: four 

當我覺得我應該得到

 
test: one 
test: two 
test: three 
test: four 

我做錯誤的東西,或者是手冊頁只是對我說謊?我知道我可以(一般來說)破解字符串,並且插入臨時的'\0'來終止字符串(除非它是一個char const *,就像這裏,我不得不復制它),但它是一個PITA (特別是如果我試圖在相同的printf中打印兩部分內容),我想知道爲什麼精度被忽略。

回答

18

您沒有設置精度,您正在設置字段寬度精度始終以格式規範中的.開頭。

printf("test: %.3s\n", test); 
+2

** facepalm **。謝謝! – rampion 2009-09-25 15:52:34

+0

... 最小值寬度... – pmg 2009-09-25 15:54:15

+0

第一個數字參數是_named_「字段寬度」或有時只是「寬度」。不過,它確實指定了最小字段寬度。 – 2009-09-25 15:59:30