1

假设我有一个structtest

struct  test
{
    char name[16];

} test;

我想阅读用户的输入并将其放在name字段中。假设用户已输入"hello"作为输入。我的代码是这样的:

struct test test1;

strcpy(test1.name, user_input);

现在名称中有 5 个字符 ( "hello"),但我希望它有 16 个字符:5 个用于实际输入,其余的空格。我怎样才能做到这一点?

4

3 回答 3

5

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: [               ]
于 2012-10-14T06:23:08.977 回答
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 可能是正确答案的问题。]

于 2012-10-14T05:52:08.063 回答
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;
}
于 2012-10-14T08:32:14.153 回答