【问题标题】:How to print right/center justified text from an index in C/C++? [duplicate]如何从 C/C++ 的索引中打印右对齐/居中对齐的文本? [复制]
【发布时间】:2020-09-05 02:08:47
【问题描述】:

我很不擅长在 C/C++ 中使用 char*'s,我要求这样的效果:

假设我有一个文本编辑器或查看器,我想在侧面显示行号。我的实现如下(如果可能,请指出其中的任何错误):

unsigned int line_number_width = 5;
char* lines = strdup(buffer->text);
char* line = strtok(lines, "\n");
unsigned line_number = 1;
while (line != NULL && line_number<= buffer->height) {
    printf("???:%.*s\n", !!line_number, line_number_width!!, buffer->width - line_number_width - 1, line);
    line = strtok(NULL, "\n");
    line_number++;
}
free(lines);

我想打印以下内容:

  1:line1
  2:line2
  3:line3
  4:line4
  5:line5
  6:line6
  7:line7
  8:line8
  9:line9
 10:line10
..........
..........
..........
..........
..........
..........
..........
..........
100:line100

注意: 是如何在同一列中对齐的。

我应该用什么替换???,以便获得以下效果,其中传递的数字包含在长度为line_number_width的矩形中,这是!!..!!之间的参数,这样传递的数字就是正确的假想的矩形?

【问题讨论】:

标签: c char-pointer


【解决方案1】:

好的,我想我得到了答案:

unsigned int line_number_width = 5;
char* lines = strdup(buffer->text);
char* line = strtok(lines, "\n");
unsigned line_number = 1;
while (line != NULL && line_number<= buffer->height) {
    printf("%*d%.*s\n", line_number_width-(unsigned int)(log10(line_number)), line_number, buffer->width - line_number_width, line);

    line = strtok(NULL, "\n");
    line_number++;
}
free(lines);

【讨论】:

  • 写错地方了。使用codereview.stackexchange.com
  • @BasileStarynkevitch 是的,我真的很抱歉,我已经根据建议的线程对其进行了编辑以达到我的最终答案。
猜你喜欢
  • 2013-10-29
  • 2014-12-29
  • 2016-02-27
  • 1970-01-01
  • 2014-10-26
  • 2018-12-08
  • 2011-05-02
  • 2011-04-18
  • 2019-02-11
相关资源
最近更新 更多