Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems calling system() in c++ [duplicate]

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

like image 482
Mudzay Avatar asked Jan 30 '26 21:01

Mudzay


1 Answers

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.

like image 102
songyuanyao Avatar answered Feb 02 '26 11:02

songyuanyao