简体   繁体   English

在 C 中重用格式说明符

[英]Reuse a format specifier in C

Is there a way to reuse a format specifier in C?有没有办法在 C 中重用格式说明符? I would like to use the same specifier for the next 20 outputs, is there an easier way than to write the specifier 20 times?我想对接下来的 20 个输出使用相同的说明符,有没有比编写说明符 20 次更简单的方法? v v

In Fortran I can do this by writing 20 in front of the specifier, so (20F10.0) would be the same as (F10.0 F10.0 F10.0...).在 Fortran 中,我可以通过在说明符前面写 20 来做到这一点,因此 (20F10.0) 将与 (F10.0 F10.0 F10.0...) 相同。 Is there something similar in C? C中有类似的东西吗?

At the risk of your preprocessor macros looking like a snake with a severe stutter and your future self wondering why on earth you've done something like this, you could (ab)use the fact that string constants can be concatenated...冒着你的预处理器宏看起来像一条严重口吃的蛇的风险,你未来的自己想知道为什么你做了这样的事情,你可以(ab)使用字符串常量可以连接的事实......

#include <stdio.h>

#define REPEAT5(s) s s s s s 
#define REPEAT4(s) s s s s
#define REPEAT20(s) REPEAT4(REPEAT5(s))

int main() {
    printf(REPEAT20("%d "), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
}

If you run this on Godbolt.org you can see the format string was correctly expanded to如果您在 Godbolt.org 上运行它您可以看到格式字符串已正确扩展为

.asciz  "%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d "
int x;
for(x=0;x<20;x++)
printf("%d", x);




It's just a diagram. In the 
body of the for loop, you 
can independently determine 
what exactly printf ( )will print. 

This should do the trick:这应该可以解决问题:

char *n_format(char *format, size_t n, char delimiter)
{
    char *result;
    int  index = 0;
    size_t len;

    if (!format)
        return (NULL);
    len = strlen(format);
    if (!(result = malloc(len * n + n)))
        return (NULL);
    for (int i = 0; i < n; ++i)
    {
        strcpy(result + index, format);
        index += len;
        result[index++] = delimiter;
    }
    result[index - 1] = '\0';
    return (result);
}

Usage:用法:

int main()
{
    char *string;
    string = n_format("%.5f", 5, ' ');
    printf("|%s|\n", string);
    // output: |%.5f %.5f %.5f %.5f %.5f|
    free(string);
    return (0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM