5
if (namelist==NULL)
{
   namelist=(char**)malloc(sizeof(char**));
   namelist[i]=name;
}
else
{
   namelist=(char**)realloc(namelist,(i+1)*sizeof(char**));
   namelist[i]=name;
}

for(i=0;i<count;i++)
{
   printf("%s\t\t%s\n",namelist[i],namelist[i]);
}

问题是如果我输入"abcdefg",作为输入"abcdefgh""abc"我会得到

abcdefg          abcdefg
abcdefgh                    abcdefgh
abc              abc

有没有办法让第二个和"abcdefgh"第二个一样排队?"abcdefg""abc"

4

3 回答 3

8

停止使用 TAB 字符 (\t) 作为分隔符,改用正确的格式规范,如果您希望字符串从第 20 列开始,请编写:

printf( "%-20s%s", namelist[i],namelist[i]);
于 2012-11-23T13:05:56.550 回答
2

尝试这个:

printf("%-20s%-20s\n",namelist[i],namelist[i]);

有关. _ _printf

于 2012-11-23T13:06:24.213 回答
0

为了保持灵活性,您可能需要使用参数化宽度:

#include <stdio.h>

typedef enum Alignment_e
{
  alignmentUndefined = -1,
  alignmentLeft = 0,
  alignmentRight,
  alignmentMax
} Alignment_t;

typedef struct Tab_s
{
  int position;
  Alignment_t alignment;
} Tab_t;

#define FORMAT_TABBED_STRING "%*s"
#define TABBED_STRING( \
  str, \
  tab \
) \
  ((tab).alignment != alignmentLeft) ?(tab).position :-(tab).position, (str)


/* test */
int main()
{
  const Tab_t tabs[] = {
    {9, alignmentLeft},
    {32, alignmentRight},
    {-1, alignmentUndefined} /* array termination; not to be used as tab descriptor */
  }; 

  char s1[] = "s1";
  char s2[] = "s2";

  printf(FORMAT_TABBED_STRING"|"FORMAT_TABBED_STRING"|\n", TABBED_STRING(s1, tabs[0]), TABBED_STRING(s2, tabs[1]));
  printf(FORMAT_TABBED_STRING""FORMAT_TABBED_STRING"\n", TABBED_STRING(s1, tabs[1]), TABBED_STRING(s2, tabs[0]));  
}
于 2012-11-23T13:35:34.243 回答