如何将C ++变量数据放入system()函数 [英] How to put a c++ variable data into system() function

查看:95
本文介绍了如何将C ++变量数据放入system()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

请看下面的代码:

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


推荐答案

仅连接开始前缀和 app 变量,然后将结果作为c样式字符串传递给 system(),如下所示:

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

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

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());

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

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

这篇关于如何将C ++变量数据放入system()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆