2

I tried to use system() in a c++ app it works very well if i do it like:

system("notepad");

But it gives error when i try to do like:

cin >> cmdlol;  
system(cmdlol);

Error:

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

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Mudzay
  • 71
  • 8

2 Answers2

11

cmdlol seemes to be std::string, which can't be converted to const char* implicitly. And std::system only accepts const char* as its argument, that's why compiler complains.

You could use std::basic_string::c_str() explicitly.

system(cmdlol.c_str());

And about why system("notepad"); works well, "notepad" is a string literal with type const char[8] (including null character), note it's not std::string and might decay to const char* when passed to std::system.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
4

std::system wants a const char*, that's a C-style array.

To convert a std::string to a const char*, you can use the function c_str().

system(cmdlol.c_str());
Rakete1111
  • 47,013
  • 16
  • 123
  • 162