sprintf ()可以做到這一點:
sprintf(test1.name,"%-15s","John Doe");
printf("[%s] length of test1.name: %ld\n",test1.name,strlen(test1.name));
sprintf(test1.name,"%-*s",(int) sizeof(test1.name) - 1,"Jane Jones");
printf("[%s] length of test1.name: %ld\n",test1.name,strlen(test1.name))
輸出:
[John Doe ] length of test1.name: 15
[Jane Jones ] length of test1.name: 15
或
#include <stdio.h>
#include <string.h>
int copy_with_pad(char *destination,const char *source, int dest_size, char pad_char)
{
int pad_ctr = 0;
if (dest_size < 1) return -1;
int source_length = strlen(source);
int data_size = dest_size - 1;
destination[data_size] = '\0';
int i = 0;
while (i < data_size)
{
if (i >= source_length)
{
destination[i] = pad_char;
pad_ctr++;
}
else
destination[i] = source[i];
i++;
}
return pad_ctr;
}
int main(void)
{
struct test {
char name[16];
};
struct test test1;
int chars_padded = copy_with_pad(test1.name,"Hollywood Dan",
sizeof(test1.name),' ');
printf("%d padding chars added: [%s]\n",chars_padded,test1.name);
chars_padded = copy_with_pad(test1.name,"The Honorable Hollywood Dan Jr.",
sizeof(test1.name),' ');
printf("%d padding chars added: [%s]\n",chars_padded,test1.name);
chars_padded = copy_with_pad(test1.name,"",16,' ');
printf("%d padding chars added: [%s]\n",chars_padded,test1.name);
}
輸出
2 padding chars added: [Hollywood Dan ]
0 padding chars added: [The Honorable H]
15 padding chars added: [ ]
是否有任何理由要做到這一點首先?你不應該把剩下的空白空間(最後一個字節應該是0),否則,你在使用字符串函數時可能會遇到問題。 – nhahtdh
是的。我正在編寫一個與linux中的「ar」命令非常相似的程序,並且需要有固定長度的字段。 – PoweredByOrange
只是讓剩下的字節爲0. – nhahtdh