2009-09-25 5 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. 

하지만 내 테스트 코드는 확인하지 않습니다 내가
 
test: one 
test: two 
test: three 
test: four 

내가 뭐하는 거지 받고해야한다고 생각하면

#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 

출력을 잘못된 것이거나 man 페이지입니다. 그냥 거짓말하는거야?

FYI : (일반적으로) 문자열을 해킹하고 '\0' 문자열을 종료 할 수 있음을 알고 있습니다. (여기서는 char const * 인 경우를 제외하고 대신 복사해야합니다.)하지만 PITA입니다. (특히 동일한 printf에서 두 부분을 인쇄하려고 할 때), 정밀도가 무시되는 이유를 알고 싶습니다.

답변

18

정밀도를으로 설정하지 않고 필드 너비를으로 설정하면됩니다. 정밀도은 항상 형식 사양에서 .으로 시작합니다.

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

** facepalm **. 감사! – rampion

+0

... 최소 너비 ... – pmg

+0

첫 번째 숫자 매개 변수의 이름은 "필드 너비"또는 때로는 "너비"입니다. 그러나 최소 필드 너비를 지정합니다. –

관련 문제