윌리엄 토틀 랜드 (Williams Totland)의 답변에 따르면 필요한 공백 만 계산하면 printf
을 사용할 수 있습니다. 나는 (그것이 비록 제한) 내 지식을 새로 고침하는 과정에있어 때문에, 메모리 관리에, 나는이 함께했다 : sprintf
또는 strncat
를 사용
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int a = 20;
char x[10] = "Hello";
char *spaces_ptr;//padding str pointer
a = (a-strlen(x))/2;
//allocate the required mem, calloc ensures zero terminated
spaces_ptr = calloc(a + 1, sizeof(char));
memset(spaces_ptr, ' ', a);//set a chars to hold spaces
//print
printf("%s%s", spaces, x);
free(spaces);//free memory
return 0;
}
도 물론 옵션입니다 ... 또는 심지어 :
char *fullStr = calloc(strlen(x) + a + 1, sizeof(char));
memset(fullStr, ' ', a);
strncpy(fullStr+a, x, strlen(x));
puts(fullStr);
free(fullStr);
이 마지막 스 니펫은 전체 답변과 마찬가지로 사후 검토입니다.어쨌든 check this codepad to see it in action
두 번째'printf' 형식 지정자에서's'를 거의 잊어 버렸습니다. –
0xF1 제안 된 수정에 감사드립니다. –