printf的返回字符串 [英] printf That Returns a String

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

问题描述

有没有如printf函数,可以返回一个字符串,而不是打印呢?我有一个在打印某种颜色的字符串的函数,但它必须是一个字符串,而不是接受如printf变量。

Is there a function like printf that can return a string instead of printing it? I have a function that prints a string in a certain color, but it has to be a string literal instead of accepting variables like printf.

// Function declaration (Assums YELLOW and NORMAL are the unix constants for terminal colors
void pYellow(char *str) {
    printf("%s%s%s", YELLOW, str, NORMAL);
}

//Function call 
void pYellow("This is a string");

如果我想在彩色打印同一个变量,它不会工作。像 pYellow(数数:%d,42); 会给出一个错误,因为它有太多的参数。和做 pYellow(的printf(字符串)); 将不会工作。

If I wanted to print in color with a variable, it wont work. Like pYellow("Num: %d", 42); will give an error, because its got too many parameters. And doing pYellow(printf("String")); won't work either.

TL:DR。我想知道,如果有,它返回一个字符串,而不是打印出来的printf的方法

TL:DR I want to know if there's a printf method that returns a string instead of printing it.

推荐答案

使用的snprintf

int snprintf(char *str, size_t size, const char *format, ...);


  • STR 是你分配的缓冲区(例如的malloc()

  • 尺寸是缓冲
  • 的大小
  • 呼叫后格式化字符串存储在 STR

  • 还有的sprintf 从来没有使用它

    • str is a buffer you allocated (e.g. malloc())
    • size is the size of that buffer
    • After the call the formatted string is stored in str.
    • There's also sprintf, never use it
    • 您也可以创建自己的的printf 般使用 V *的printf 系列函数的功能。这个简单的例子:

      Also you can create you own printf-like functions using the v*printf family of functions. Simplest example for this:

      #include <stdarg.h>
      // required for va_list, va_start, va_end
      
      void customPrintf(const char* format, /* additional arguments go here */ ...)
      {
          va_list args;
          va_start(args, format);
          // set color here (for example)
          vprintf(format, args);
          // reset color
          va_end(args);
      }
      

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

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