Search code examples
c++string-literals

error: invalid conversion from 'int' to 'const char*' [-fpermissive] with a system command line


I'm trying run a netsh command with the system() function in C++.

Here is my code:

#include<iostream> // cin / cout
#include<stdlib.h> // system()
using namespace std;

int main(){

    system('netsh interface show interface | findstr /C:"Wi-Fi" /C:"Name"');

}

I think that I need to add something before the 'netsh to solve this error but I don't know what character, I already try: system(L'netsh interface show interface | findstr /C:"Wi-Fi" /C:"Name"'); but no success,


Solution

  • You are passing in a multi-character literal instead of a string literal. Using single-quotes '...' creates a single char, which is a numeric type that can be promoted to int, that is why you are getting the error about an int being passed in where a const char* is expected. system() expects a null-terminated C-style string instead, ie an array of char values ending with the '\0' character. In string literal form, you use double-quotes "..." instead to create such an array.

    You need to replace the ' characters with ". And then you also need to escape the inner " characters using \, eg:

    system("netsh interface show interface | findstr /C:\"Wi-Fi\" /C:\"Name\"");
    

    Alternatively, in C++11 and later, you can use a raw string literal instead to avoid escaping the inner " characters:

    system(R"(netsh interface show interface | findstr /C:"Wi-Fi" /C:"Name")");