0

I'm having trouble getting system() to run a command in a string variable.

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() just takes an int in hours, converts it into seconds and returns an int in seconds. Everything runs fine, no errors, until it reaches system(cmd);. The compiler then spits out this error:

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

Here are my includes:

#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
2
  • 2
    system(cmd.c_str()); Commented Jul 24, 2013 at 23:39
  • Why don't you put it as an answer when it is the answer? Commented Jul 24, 2013 at 23:43

2 Answers 2

5

I know this has already been answered by comments, but not really explained:

The system function is a C function. It does not "understand" C++ style strings. For that, you will need to use the c_str() function. In other words, you need system(cmd.c_str());.

This applies to a large number of C style functions that are still available in C++, since one of the main features of C++ is that you can still use traditional C-code (for the most part) in C++. So, the same applies to almost any C style function that takes a string - printf("cmd=%s", cmd.c_str()); would print what your command is.

It would be possibe to write your own wrapper function:

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

Now, the rest of your code can use system with a regular C++ style string.

Sign up to request clarification or add additional context in comments.

Comments

2

system takes a C string not a std::string, so you must call the c_str function first.

system(cmd.c_str());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.