假设我有一个名为struct
的{{1}}:
test
我想阅读用户的输入并将其放在struct test
{
char name[16];
} test;
字段中。假设用户输入了name
作为输入。我的代码是这样的:
"hello"
现在名称中有5个字符(struct test test1;
strcpy(test1.name, user_input);
),但我希望它有16个字符:实际输入为5,其余为空格。我怎样才能做到这一点?
答案 0 :(得分:4)
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: [ ]
答案 1 :(得分:2)
我认为显而易见的是:
memset(test1.name, ' ', 16);
size_t len = min(16, strlen(user_input));
memcpy(test1.name, user_input, len);
如果你想零填充任何多余的空间,那就更简单了:
strncpy(test1.name, user_input, 16);
[我第一次看到/听到有人提出一个问题,strncpy
可以实际上是一个正确答案。]
答案 2 :(得分:0)
// first remember
// that a character array of length 16 can only hold a string of 15
// chars because it needs the trailing zero
// this program puts in the user input (you should check that it is short enough to fit)
// then puts in the spaces, one at a time, then the terminating zero
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name [16]; // room for 15 chars plus a null terminator
char word [] = "hello"; // user input
strcpy(name,word); // copy user input to name
int i;
for (i = strlen(name); i < (sizeof(name)-1); i++) {
name[i] = ' '; // pad with blanks
}
name[sizeof(name)-1] = 0; // string terminator
printf("name = \"%s\"\n",name);
return 0;
}