我希望能够创建一个模板字符串,然后像这样使用它:
int execute_command(char *cmd) {
//...
}
char *template_command = "some_command %s some_args %s %d";
char *actual_command = template_command % (cmd1, arg1, 123);
// error, how do I do that?
int res = execute_command(actual_command);
最佳答案
如果您知道 actual_command
的最大长度,那么您可以使用以下任一方法:
char actual_command[MAX_LEN+1];
// Option #1
sprintf(actual_command, template_command, cmd1, arg1, 123);
// Option #2
snprintf(actual_command, MAX_LEN+1, template_command, cmd1, arg1, 123);
如果 MAX_LEN
没有被正确定义,那么:
- 选项 #1 将导致未定义的行为(可能是运行时异常)
- 选项 #2 将产生不正确的结果(
actual_command
的内容)
关于创建一个 "template"(格式)字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25831456/