在系统函数中输入字符串

entering a string into the system function

本文关键字:输入 字符串 函数 系统      更新时间:2023-10-16

我想用c++编写一个程序,提示用户输入一个网址,然后在该地址的命令提示符中执行ping命令。在代码中,我使用cin命令将web地址转换为一个名为n的字符串变量,并将其添加到同一变量中的"ping"中,但是,我无法将字符串输入系统函数。下面是代码:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    string ping;
    string n;
    cout << "Enter the link you want to ping ";
    cin >> ping;
    n = "ping "+ping;
    cout << n;
    system(n);
    return 0;
}

如何将变量n中的字符串输入到系统函数中?

system是C函数,

int system( const char *command );

它不知道c++ std::string,你可以传递const char*给它:

更新
system(n);

system(n.c_str());