将字符串变量放入system()时出错

时间:2013-07-24 23:38:35

标签: c++ string stream char

我无法让system()在字符串变量中运行命令。

ostringstream convert;
convert << getSeconds(hours);
string seconds = convert.str();    /* converts the output of 'getSeconds()' into
                                      a string and puts it into 'seconds' */

string cmd = "shutdown /s /t " + seconds;

system(cmd);

getSeconds()只需要一个小时的int,将其转换为秒并以秒为单位返回一个int。一切都运行良好,没有错误,直到达到system(cmd);。编译器然后吐出这个错误:

error: cannot convert 'std::string {aka std::basic_string<char>}' to
'const char*' for argument '1' to 'int system(const char*)'

以下是我的包含:

#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>

2 个答案:

答案 0 :(得分:5)

我知道评论已经回答了这个问题,但没有真正解释过:

system函数是C函数。它不“理解”C ++样式字符串。为此,您需要使用c_str()功能。换句话说,您需要system(cmd.c_str());

这适用于C ++中仍然可用的大量C样式函数,因为C ++的一个主要特性是您仍然可以在C ++中使用传统的C代码(大部分)。因此,这几乎适用于任何采用字符串的C样式函数 - printf("cmd=%s", cmd.c_str());将打印您的命令。

可以编写自己的包装函数:

int system(const std::string &cmd)
{
   return system(cmd.c_str());
}

现在,您的其余代码可以将system与常规C ++样式字符串一起使用。

答案 1 :(得分:2)

系统采用C字符串而不是std :: string,因此必须首先调用c_str函数。

system(cmd.c_str());