python - 如何在C中打印多行

标签 python c range tuples

我有一段Python代码,内容如下:

template = \
"""
                 %2s  %2s  %2s

                 %2s   R  %2s

                 %2s  %2s  %2s

    %2s  %2s  %2s   %2s  %2s  %2s   %2s  %2s  %2s    %2s  %2s  %2s

    %2s   B  %2s   %2s   W  %2s   %2s   G  %2s    %2s   Y  %2s

    %2s  %2s  %2s   %2s  %2s  %2s   %2s  %2s  %2s    %2s  %2s  %2s

                 %2s  %2s  %2s

                 %2s   O  %2s

                 %2s  %2s  %2s
    """

print template % tuple(range(1, 49))

我正在尝试将上面的代码转换为C(是的,我刚刚开始学习,这可能是不言而喻的),并且在我的一生中,找不到任何可以帮助我的文档。

我已经尝试过使用 Cython,但最终得到了非常长的代码,对我来说,在我的程序中实现并不实际。我也在Stackoverflow上搜索了很长一段时间,没有结果。如果我错过了什么,请给我发送链接。

最佳答案

我想不出一种可移植的方法来生成参数列表,所以我想不出比键入整个列表更好的简单解决方案,例如 printf(template, 1, 2, 3, 4, 5, 6, ...,49)。

另一种解决方案是手动浏览模板并执行以下操作:

#include <stdio.h>
#include <string.h>

void print_template_with_range(char *template, int start, int end) {
  int i = 1;
  char *str = strdup(template);
  char *cur = str;
  char *pos;
  while ((pos = strstr(cur, "%2s")) != NULL) {
    *pos = '\0';
    printf("%s", cur);
    printf("%2d", i++);
    cur = pos + 3;
  }
  printf("%s", cur);
  free(str);
}

int main() {
char* format_string = "\n\
             %2s  %2s  %2s\n\
\n\
             %2s   R  %2s\n\
\n\
             %2s  %2s  %2s\n\
\n\
%2s  %2s  %2s   %2s  %2s  %2s   %2s  %2s  %2s    %2s  %2s  %2s\n\
\n\
%2s   B  %2s   %2s   W  %2s   %2s   G  %2s    %2s   Y  %2s\n\
\n\
%2s  %2s  %2s   %2s  %2s  %2s   %2s  %2s  %2s    %2s  %2s  %2s\n\
\n\
             %2s  %2s  %2s\n\
\n\
             %2s   O  %2s\n\
\n\
             %2s  %2s  %2s\n\
    ";
print_template_with_range(format_string, 1, 49);
return 0;
}

产品:

              1   2   3

              4   R   5

              6   7   8

 9  10  11   12  13  14   15  16  17    18  19  20

21   B  22   23   W  24   25   G  26    27   Y  28

29  30  31   32  33  34   35  36  37    38  39  40

             41  42  43

             44   O  45

             46  47  48

关于python - 如何在C中打印多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22590686/

相关文章:

python - 如何从具有纵横比的视频中调整帧的大小

python - 让 Gunicorn 在 80 端口上运行

c - R中15个数字的排列

c - EOF 在...EOF 之前到达

c - 免费 rtos 中 xTaskAbortDelay 函数的用途是什么?

一系列数字的 MySQL GROUP_CONCAT

python - 崇高文本3 : How do I make a keybind to enable and disable Anaconda linting?

python - 返回负 float 和正 float 之和

javascript - 输入超过999时JS数字范围错误

MySQL:任何改进最佳匹配存储过程的建议