【问题标题】:Trying to pass string variables into std::system试图将字符串变量传递到 std::system
【发布时间】:2019-12-11 23:14:47
【问题描述】:

我的代码:

std::string mail;
std::string password;
std::system("mkdir ~/.cache/pbt");
std::cout << "Enter your accounts mail" << std::endl;
std::cin >> mail;
std::cout << "Now enter your accounts password";
std::cin >> password;
std::system("perl zap2xml.pl -u " + mail + " -p " + password + " -o ~/.cache/pbt");

当我尝试编译这段代码时:

编译器说

main.cpp:13:62: error: cannot convert ‘std::__cxx11::basic_string<char>’ to ‘const char*’
   13 | std::system("perl zap2xml.pl -u " + mail + " -p " + password + " -o ~/.cache/pbt");
      |             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
      |                                                              |
      |                                                              std::__cxx11::basic_string<char>
In file included from /usr/include/c++/9.2.0/cstdlib:75,
                 from /usr/include/c++/9.2.0/ext/string_conversions.h:41,
                 from /usr/include/c++/9.2.0/bits/basic_string.h:6493,
                 from /usr/include/c++/9.2.0/string:55,
                 from /usr/include/c++/9.2.0/bits/locale_classes.h:40,
                 from /usr/include/c++/9.2.0/bits/ios_base.h:41,
                 from /usr/include/c++/9.2.0/ios:42,
                 from /usr/include/c++/9.2.0/ostream:38,
                 from /usr/include/c++/9.2.0/iostream:39,
                 from main.cpp:1:
/usr/include/stdlib.h:784:32: note:   initializing argument 1 of ‘int system(const char*)’
  784 | extern int system (const char *__command) __wur;
      |                    ~~~~~~~~~~~~^~~~~~~~~

看起来 std::system 无法读取 std::string 变量,只能读取 const char* ,但必须有某种方法可以做到这一点。

我该如何解决这个问题?

【问题讨论】:

  • 您应该将这些字符串放在单引号内,因为这些字符串可能包含特殊字符或恶意脚本。

标签: c++ linux c++11 system std


【解决方案1】:

std::system()const char* 作为输入,但您正试图将std::string 传递给它。 std::string 不能隐式转换为const char*,因此会出现编译器错误。但是,您可以使用字符串的c_str() 方法来获取const char*,例如:

std::string cmd = "perl zap2xml.pl -u '" + mail + "' -p '" + password + "' -o ~/.cache/pbt";
std::system(cmd.c_str());

或者:

std::system(("perl zap2xml.pl -u '" + mail + "' -p '" + password + "' -o ~/.cache/pbt").c_str());

注意mailpassword 字符串被包裹在单引号内。这是因为这两个参数可能包含特殊字符或恶意代码,因此应进行相应的转义。

【讨论】:

  • 还要注意系统调用shell解释器,所以如果密码(特别是)可能包含可能被shell特殊处理的字符,甚至是空格,那么你需要引用它和/或转义这些字符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多