如何在C中打印多行
我有一段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上搜索了很久,但没有找到答案。如果我错过了什么,请给我发个链接。
2 个回答
0
在Python中,你可以把一堆数据扔给一个字符串,然后就会出现神奇的效果。这就是高级语言的乐趣所在。
C语言就没有这种乐趣,也不是一种高级语言。
在C语言中,你需要先把想要打印的数据放进一个数组里,然后通过循环来调用printf和/或puts,逐行或逐字符地输出你想要的内容,或者两者结合。
如果你想做类似上面那样的事情:
char* format_string = " \
%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 \
";
printf(format_string, t[0], t[1], ...);
1
我想不出一种方便的方法来生成参数列表,所以我想不到比直接输入整个列表更简单的解决办法,比如写成 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