gpt4 book ai didi

c - 文本对齐C语言

转载 作者:太空宇宙 更新时间:2023-11-04 01:58:07 24 4
gpt4 key购买 nike

我必须解决一个涉及左对齐字符串长度和前导零的问题。

我有下表:

  1. 开始
  2. 关闭
  3. 连接
  4. 删除
  5. 结束
  6. 初始化
  7. 打印

这是由一个简单的程序产生的。我的问题是找出如何像这样转换它:

enter image description here

它必须完全对齐。

我必须使用左对齐而不是“制表符”(\t)。另外,我必须计算字符串长度。到目前为止,我的代码如下:

 int i;

int long temp;

char a = 'a';

char command[][12]= {

"BEGIN", "CLOSE", "CONCATENATE", "DELETE",
"END" , "INITIALIZE", "PRINT", "WRITE"

};

int main()

{

printf("a/a \tCommand \tLength\n");

for (i=0 ; i<8 ;i++){

temp = strlen(command[i]);

printf("%c. %10s %ld \n",a, command[i], temp);

a++;

}

printf("\n");

return 0;

}

我试图在 printf 中添加一个整数而不是数字 ( 10 ),但我不知道这是否是正确的解决方案。

例如这样的事情:

    printf("%c. %10s %%dld \n",a, command[i], integer,  temp);

感谢任何帮助。谢谢。

最佳答案

来自 printf 的手册:

The field width

An optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int. (emphasis mine)

所以你可以这样写:

printf("%c. %10s %*ld \n",a, command[i], temp, integer);

关于c - 文本对齐C语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30997935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com