<分区>
是否可以在另一个字符串标识符中包含一个字符串标识符,并打印整个内容?例如:
int main()
{
char *str1 = "%s says:";
char *name = "John";
printf("%s\n", str1, name);
return(0);
}
我预期的输出是 John says:
。我怎么会 printf 或 sprintf 这样的东西?
<分区>
是否可以在另一个字符串标识符中包含一个字符串标识符,并打印整个内容?例如:
int main()
{
char *str1 = "%s says:";
char *name = "John";
printf("%s\n", str1, name);
return(0);
}
我预期的输出是 John says:
。我怎么会 printf 或 sprintf 这样的东西?
最佳答案
不,printf
不能那样工作。您必须在两个不同的阶段执行此操作:
const char *fmt = "%s says: ";
char result1[SIZE]; // where SIZE is large enough to hold the result
sprintf( result, fmt, "John" ); // result now contains "John says: "
printf( "%s\n", result ); // writes "John says: " to standard output
我不得不多次对此进行修改,我需要动态构建格式字符串。这很容易。
关于c - 另一个字符串中的字符串标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38731053/