将格式化的字符串附加到 C 中的字符串,无需指针运算 [英] Append formatted string to string in C without pointer arithmetic

查看:14
本文介绍了将格式化的字符串附加到 C 中的字符串,无需指针运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个非常简单的 C 函数来说明我想要简化的内容:

I wrote a very simple C function to illustrate what I would like to simplify:

void main(int argc, char *argv[])
{
    char *me = "Foo";
    char *you = "Bar";
    char us[100];
    memset(us, 100, 0x00);

    sprintf(us, "You: %s\n", you);
    sprintf(us + strlen(us), "Me: %s\n", me);
    sprintf(us + strlen(us), "We are %s and %s!\n", me, you);
    printf(us);
}

是否有标准库函数来处理我正在用 sprintf 做的事情并推进指针?

Is there a standard library function to handle what I'm doing with sprintf and advancing the pointer?

推荐答案

sprintf 返回写入的非 NUL 字符数.

sprintf returns the number of non-NUL characters written.

int len = 0;
len += sprintf(us+len, ...);
len += sprintf(us+len, ...);
...

这篇关于将格式化的字符串附加到 C 中的字符串,无需指针运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆