在C语言中格式化字符串

5
通常,您可以像这样在C中打印字符串...
printf("No record with name %s found\n", inputString);

但我想把它变成一个字符串,怎么做?我正在寻找像这样的东西..

char *str = ("No record with name %s found\n", inputString);

I hope it is clear what I am looking for...


3
请自行购买《C程序设计语言》(Kernigham和Ritchie合著),这会对您有所帮助。 - Pete
http://www.eskimo.com/~scs/cclass/cclass.html - Sinan Ünür
5个回答

30

一个选择是使用sprintf,它的用法和printf相同,但第一个参数是指向结果字符串应放置在其中的缓冲区的指针。

更好的选择是使用snprintf,它需要一个额外的参数包含缓冲区长度,以防止缓冲区溢出。例如:

char buffer[1024];
snprintf(buffer, 1024, "No record with name %s found\n", inputString);

10

您需要使用sprintf函数族。它们的一般格式如下:

char output[80];
sprintf(output, "No record with name %s found\n", inputString);

然而,sprintf 单独使用是非常危险的。它容易出现所谓的缓冲区溢出问题。这意味着sprintf不知道你提供的 output 字符串有多大,因此它会愉快地将比可用内存更多的数据写入其中。例如,下面的代码可以编译通过,但会覆盖有效内存,并且无法让 sprintf 知道它正在做错什么:

char output[10];
sprintf(output, "%s", "This string is too long");
解决方法是使用一个带有长度参数的函数snprintf
char output[10];
snprintf(output, sizeof output, "%s", "This string is too long, but will be truncated");

如果您正在使用Windows系统,建议使用_sntprintf及其相关函数,以避免输入或输出字符串溢出。


3
这是一个作业问题,我想强调的是 sizeof output 只会给出 char 数组中元素的个数 - 通常做法是使用 sizeof array / sizeof array[0],它不依赖于不同类型的大小而能正常工作。此外,它也适用于 char 数组。 :) - Lucas Jones
好观点。即使如此,在某些常见情况下,例如将array传递给函数时,它也可能失败--此时,在任何现代系统上,sizeof array都为4或8,而不管其中的元素数量和大小。真正的解决方案是使用std::vector或类似的东西,并完全避免整个混乱。 - Benjamin Pollack

7

既然这是一份作业 (感谢你标记它为作业),我建议你仔细研究...printf()函数族。

我相信你会找到解决方法的 :)


3
好的,看起来别人已经剥夺了你发现的乐趣 :) - Remo.D
1
对于正确回答作业问题,无论如何都要点个赞。 - Daniel Pryden

3

请查看 sprintf (见下文)。

int n = sprintf(str, "No record with name %s found\n", inputString);

3

使用

sprintf(str, "No record with name %s found\n", inputString);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接