在系统( " " 中使用C++变量;

Use C++ variables inside System("");

本文关键字:C++ 变量 系统      更新时间:2023-10-16

有没有办法在命令中使用变量:system("..."(;?例如,我试过这个,但它不起作用:

int main ()
{
int x=5;
system("echo Number " x " is my favorite number.");
return 0;
}

我也试过这个

system("echo Number " << x << " is my favorite number.");

而且效果也不好。 谢谢。

注意:我刚刚开始学习C++我还是初学者。

如果您使用的是C++11,则有一个方便的std::to_string

std::string part_a("echo Number "), part_b(" is my favorite number");
system((part_a + std::to_string(x) + part_b).c_str());

这将调用重载的operator+()以进行class basic_string

传统方法是将其打印到std::stringstream并使用基础字符串。