【问题标题】:How do you write formatted output, as from printf, into a string?如何将格式化输出(如 printf)写入字符串?
【发布时间】:2020-06-08 07:13:54
【问题描述】:
const char* strrep(listing list) {
//https://stackoverflow.com/q/4836534/9295513
char* retVal = //...
return retVal;
}

我有一个名为listing 的结构类型。有没有一种方法来格式化元素,就像用("%d %d %s...", list->elem_one, list->elem_two, list->elem_three...) 调用printf 一样,但将输出写入char 的数组而不是标准输出?

【问题讨论】:

    标签: c formatting char constants


    【解决方案1】:

    如果我没看错,您希望打印到缓冲区而不是输出到控制台或文件。如果是这种情况,你会想使用sprintf,或者它是有界表亲snprintf。以下是来自cplusplus 网站的示例:

    #include <stdio.h>
    
    int main ()
    {
      char buffer [50];
      int n, a=5, b=3;
      n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
      printf ("[%s] is a string %d chars long\n",buffer,n);
      return 0;
    }
    

    请注意,sprintf 会自动附加一个空终止符,但您仍然需要确保字符串的总长度可以适合给定的缓冲区。

    【讨论】:

      【解决方案2】:

      你想要的函数是snprintf。它创建一个格式化字符串并将其写入给定大小的给定char * 参数,而不是标准输出。

      例如:

      int len = snprintf(NULL, 0, "%d %d %s...", list->elem_one, list->elem_two, list->elem_three...);
      char *retVal = malloc(len+1);
      snprintf(retval, len+1, "%d %d %s...", list->elem_one, list->elem_two, list->elem_three...);
      

      第一次调用用于确定需要多少空间。然后您可以分配适当的空间并再次调用snprintf以创建格式化字符串。

      【讨论】:

        猜你喜欢
        • 2012-01-26
        • 1970-01-01
        • 1970-01-01
        • 2014-11-06
        • 1970-01-01
        • 1970-01-01
        • 2021-12-13
        • 2018-01-01
        • 2018-05-02
        相关资源
        最近更新 更多