将变量放入 "quotation marks"

Getting variables into "quotation marks"

我目前正在努力获取 "quoatation marks"
内的变量 我的代码如下所示:

const char* cmd = "ffmpeg -r 25 -f rawvideo -pix_fmt rgba -s 1280x720 -i - "
"-threads 0 -preset fast -y -pix_fmt yuv420p -crf 21 -vf vflip output.mp4";

现在我得到两个名为 "previewWidth" 和 "previewHeight" 的 int 变量,我希望它们替换“1280x720”。 但我不知道该怎么做

谢谢,
马可

int previewWidth, previewHeight;
// ...
char cmd[1024];
sprintf (cmd, "ffmpeg -r 25 -f rawvideo -pix_fmt rgba -s %dx%d -i - "
    "-threads 0 -preset fast -y -pix_fmt yuv420p -crf 21 -vf vflip output.mp4",
    previewWidth, previewHeight);

因为这是 C++,你最好使用 std::string

使用sprintf.

你的情况:

unsigned int previewWidth = /* init */;
unsigned int previewHeight = /* init */;

const char* raw_cmd = "ffmpeg -r 25 -f rawvideo -pix_fmt rgba -s %ux%u -i - "
"-threads 0 -preset fast -y -pix_fmt yuv420p -crf 21 -vf vflip output.mp4";

char result_cmd[256];

sprintf(result_cmd, raw_cmd, previewWidth, previewHeight);

现在,result_cmd 包含您的结果命令,但这两个 %u 分别替换为 previewWidthpreviewHeight 的值。

空终止符由 sprintf() 自动附加。

还有一件事,我假设,widthheight 不能为负数。如果可以,请将 %u (unsigned) 替换为 %d (decimal).

有关可用于 C(++) 中许多打印函数的说明符的完整列表,请参阅 this page

std::string get_command(int previewWidth, int previewHeight) {
  std::stringstream ss;
  ss << "ffmpeg -r 25 -f rawvideo -pix_fmt rgba -s ";
  ss << previewWidth << 'x' << previewHeight;
  ss << "-i - -threads 0 -preset fast -y -pix_fmt yuv420p -crf 21 -vf vflip output.mp4";
  return ss.str();
}

然后在使用点:

const std::string cmd = get_command(previewWidth, previewHeight);

并调用 cmd.c_str() 获取原始 const char* 以传递给 API.

请注意,这不是最快的解决方案,但您将调用外部进程来进行音频文件操作(可能写入磁盘),因此 stringstream 相对较慢应该无关紧要.

stringstream 使建立字符串变得非常容易,而且非常安全。与替代方案相比,它的速度相当慢,但轻松和安全往往胜过速度。


高级技术:

在 C++11 中,我有时会使用 lambda:

const std::string cmd = [&]{
  std::stringstream ss;
  ss << "ffmpeg -r 25 -f rawvideo -pix_fmt rgba -s ";
  ss << previewWidth << 'x' << previewHeight;
  ss << "-i - -threads 0 -preset fast -y -pix_fmt yuv420p -crf 21 -vf vflip output.mp4";
  ss.str();
}();

并在其中构建字符串而不是创建辅助函数,如果我认为此任务不值得辅助函数的话。以上是创建跟踪消息等的有用技术,或者在我将字符串构建操作重构为它自己的函数之前进行简单的"scratch"工作。