问题
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