创建Ç格式的字符串(不打印它们) [英] Creating C formatted strings (not printing them)

查看:95
本文介绍了创建Ç格式的字符串(不打印它们)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受字符串的函数,即:

 无效log_out(字符*);

在调用它,我需要动态创建的格式化字符串,如:

  INT I = 1;
log_out(一些文本%D,我);

如何在ANSI C这样做吗?


只是,因为的sprintf()返回一个整型,这意味着我必须写至少3个命令,如:

 的char * S;
sprintf的(S,%d个\\ T%D,IX,IY);
log_out(多个);

要缩短这个办法吗?


解决方案

使用的sprintf

  INT的sprintf(的char * str中,为const char *格式,...);


  

写格式的数据串组成具有相同的文本字符串
  如果格式是printf使用,将被印刷的,但不是
  被打印,内容被存储在所述缓冲器中的C字符串
  由海峡指出。


  
  

缓冲区的大小应该足够大,以包含整个
  得到的字符串(见的snprintf一个更加安全的版本)。


  
  

终止空字符后自动添加
  内容。


  
  

format参数后,该函数需要至少多
  根据需要格式的其他参数。


参数:

 海峡


  

的指针,其中所得的C-字符串存储的缓冲器。缓冲区
  应该足够大,以容纳结果字符串。


 格式


  包含遵循相同的格式字符串

C字符串
  规格在printf中(详见printf的)。

格式

  ...(更多参数)


  

根据格式字符串,函数可能期望的序列
  额外的参数,每个都包含一个值被用来代替一
  格式说明格式字符串(或指向存储
  位置,对于n)。应该有至少尽可能多的这些论点
  如在格式说明指定的值的数目。额外
  参数由函数忽略。


示例:

  //分配存储空间
字符*参考hello world =(字符*)malloc的(13 * sizeof的(炭));
//输出Hello World!在参考hello world
sprintf的(参考hello world%s%S!,你好,世界);

I have a function that accepts a string, that is:

void log_out(char *);

In calling it, I need to create a formatted string on the fly like:

int i = 1;
log_out("some text %d", i);

How do I do this in ANSI C?


Only, since sprintf() returns a int, this means that I have to write at least 3 commands, like:

char *s;
sprintf(s, "%d\t%d", ix, iy);
log_out(s);

Any way to shorten this?

解决方案

Use sprintf.

int sprintf ( char * str, const char * format, ... );

Write formatted data to string Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.

The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version).

A terminating null character is automatically appended after the content.

After the format parameter, the function expects at least as many additional arguments as needed for format.

Parameters:

str

Pointer to a buffer where the resulting C-string is stored. The buffer should be large enough to contain the resulting string.

format

C string that contains a format string that follows the same specifications as format in printf (see printf for details).

... (additional arguments)

Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.

Example:

// Allocates storage
char *hello_world = (char*)malloc(13 * sizeof(char));
// Prints "Hello world!" on hello_world
sprintf(hello_world, "%s %s!", "Hello" "world");

这篇关于创建Ç格式的字符串(不打印它们)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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