如何将 C++ 变量数据放入 system() 函数

How to put a c++ variable data into system() function

如何将 C++ 变量数据放入 system() 函数中?

看下面的代码:

#include <iostream>
#include <windows.h>

using namespace std;

int main()
{
  cout << "name the app u want to open";

  string app;

  cin >> app;

  system("start app"); // I know this will not work! But how to make it will?
  return 0;
}

将两者连接起来,然后用 c_str():

std::string 中取出 C 字符串
system(("start " + app).c_str());

只需连接 "start" 前缀和 app 变量,并将结果作为 c 风格字符串传递给 system(),如下所示:

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    cout<<"name the app u want to open";

    string app;
    cin>>app;

    const string cmd = "start " + app;

    system(cmd.c_str()); // <-- Use the .c_str() method to convert to a c-string.
    return 0;
}

您可以使用相同的串联技巧将 args and/or 添加到命令的文件路径:

const string cmd = "start C:\Windows\System32\" + app + " /?";

system(cmd.c_str());

上面的示例 cmd 将在文件路径和“/?”前面加上前缀。命令行参数。

对于您在评论中提供的示例,您可以这样做:

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    cout << "Enter the profile name: ";

    string profile;
    cin >> profile;

    const string cmd = "netsh wlan connect name=\"" + profile + "\"";

    system(cmd.c_str());
    return 0;
}