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

放肆的年华 提交于 2019-12-22 12:45:34

问题


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

Look at the code below:

#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;
}

回答1:


Simply concatenate the "start" prefix and app variable, and pass the result to system() as a c-style string, like this:

#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;
}

You can use the same concatenation trick to add args and/or the file path to the command:

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

system(cmd.c_str());

The example cmd above will prepend the file path and "/?" command line argument.

For your example provided in the comments, you can do something like this:

#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;
}



回答2:


Concatenate the two, then get the C string out of the std::string with c_str():

system(("start " + app).c_str());


来源:https://stackoverflow.com/questions/41242820/how-to-put-a-c-variable-data-into-system-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!