I am getting an error when i try to compile this code

int StartProgram(string sProgramName){      
ShellExecute(NULL, NULL, sProgramName, NULL, NULL, SW_SHOW);
5 Years
Discussion Span
Last Post by MasterHacker110

If you're using LPCWSTR in the first place, you should also be using std::wstring rather than std::string. Then you can just use the c_str() method from std::wstring directly. It's certainly possible to convert the latter into the former, but it's fair to say that not having to do a conversion is the better option if you can manage it:

#include <string>
#include <vector>
#include <Windows.h>

namespace strings {
    std::wstring widen(const std::string& s)
        std::vector<wchar_t> buf(MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.size() + 1, 0, 0));

        MultiByteToWideChar(CP_ACP, 0, s.c_str(), s.size() + 1, &buf[0], buf.size());

        return std::wstring(&buf[0]);
Votes + Comments
You should still consider checking s.empty()... and return a std::wstring() directly.

But, in continuation to deceptikon's reply, if you just want to be able to call ShellExecute while enabling you to pass your sProgramName variable as an argument, you can use its ANSI version without much hassles, e. g. ShellExecuteA(NULL, NULL, &sProgramName[0], NULL, NULL, SW_SHOW);

Votes + Comments
this is the solution for your problem

The problem is that we need to know if the std::string() holds the Windows CP or UTF8, or something else... Decoding is different for each codepage. Also look into std::wstring_convert for UTF8.

@triumphost's solution is unsafe in regards to multibyte std::string.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.