适用于 Linux 的 c++ 上的代理脚本



我有一个代码,可以在Linux上启用代理。它应该像这样工作:我正在启动程序,将IP:port写入("停止"以禁用代理(,程序写入终端export http_proxy://(entered proxy),如果我输入了"停止",它会写unset http_proxy.这是代码:

#include <iostream>
using namespace std;
int main(){
char proxy[20];
char choice;
cout << "Enter ip:port ('stop' to disable): ";
cin >> proxy;
if(proxy != "stop"){
cout << "Do you want to use it as ftp(y/n): "
cin >> chioce;
}
if(proxy == "stop"){
system("unset http_proxy");
system("unset ftp_proxy");
}
else if(choice == 'y'){
system("export http_proxy=http:/"+'/'+proxy+'/');
system("export ftp_proxy=http:/"+'/'+proxy+'/');
}
else{
system("export http_proxy=http:/"+'/'+proxy+'/');
}
}

但是当我使用 g++ 编译时,我收到此错误:

error: invalid operands of types ‘const char*’ and ‘char [20]’ to binary ‘operator+’

这是我第一次和""+a+"".你能帮帮我吗?

您的错误是由于您无法使用+来连接字符串文字。最好的办法是使用std::string来构建字符串。

system(("export http_proxy=http:/"s + '/' + proxy + '/').c_str());

proxy也应该是一个std::string. 这样,您就不必担心要制作的大小或缓冲区溢出。

此外,正如Sam Varshavchik指出的那样,这无论如何都不会做你想要的。system()创建一个具有自己环境的子进程;一旦通话完成,它就会消失。

最新更新