c函数返回格式化的字符串 [英] c function to return formatted string

查看:85
本文介绍了c函数返回格式化的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

writeLog(printf("This is the error: %s", error));

所以我正在寻找一个返回格式化字符串的函数.

so i am looking for a function which returns a formatted string.

推荐答案

鉴于不存在这样的函数,考虑一种稍微不同的方法:使 writeLog 类似 printf,即取一个字符串和一个变量数论据.然后,让它在内部格式化消息.这将解决内存管理问题,并且不会破坏 writeLog 的现有用途.

Given no such function exists, consider a slightly different approach: make writeLog printf-like, i.e. take a string and a variable number of arguments. Then, have it format the message internally. This will solve the memory management issue, and won't break existing uses of writeLog.

如果您觉得这可行,您可以使用以下方法:

If you find this possible, you can use something along these lines:

void writeLog(const char* format, ...)
{
    char       msg[100];
    va_list    args;

    va_start(args, format);
    vsnprintf(msg, sizeof(msg), format, args); // do check return value
    va_end(args);

    // write msg to the log
}

这篇关于c函数返回格式化的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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