Search code examples
c++c++11consolesystem

Problems calling system() in c++


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*)'|


Solution

  • 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.