windowsvisual-c++ofstreamwofstream

Wide Char To Multi-Byte


I'm trying to convert wide char into multi-byte. It's only on yje myfile part. The rest works fine.I can't use wofstream because I am using ofstream in several places, so I am left with this.

void PrintBrowserInfo(IWebBrowser2 *pBrowser) {
BSTR bstr;
pBrowser->get_LocationURL(&bstr);
std::wstring wsURL;
wsURL = bstr;

size_t DSlashLoc = wsURL.find(L"://");
if (DSlashLoc != wsURL.npos)
  {
  wsURL.erase(wsURL.begin(), wsURL.begin() + DSlashLoc + 3);
  }
  DSlashLoc = wsURL.find(L"www.");
  if (DSlashLoc == 0)
{
wsURL.erase(wsURL.begin(), wsURL.begin() + 4);
}
DSlashLoc = wsURL.find(L"/");
if (DSlashLoc != wsURL.npos)
{
wsURL.erase(DSlashLoc);
}
wprintf(L"\n   URL: %s\n\n", wsURL.c_str());
char LogURL = WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, NULL, 0,  NULL, NULL); 
    myfile << "\n   URL:" << LogURL;
    SysFreeString(bstr);
}

void EnumExplorers() {
CoInitialize(NULL);
SHDocVw::IShellWindowsPtr spSHWinds;
IDispatchPtr spDisp;
if (spSHWinds.CreateInstance(__uuidof(SHDocVw::ShellWindows)) == S_OK) {
    long nCount = spSHWinds->GetCount();
    for (long i = 0; i < nCount; i++) {
        _variant_t va(i, VT_I4);
        spDisp = spSHWinds->Item(va);
        SHDocVw::IWebBrowser2Ptr spBrowser(spDisp);
        if (spBrowser != NULL) {
            PrintBrowserInfo((IWebBrowser2 *)spBrowser.GetInterfacePtr());
            spBrowser.Release();
        }
    }
} else {
    puts("Shell windows failed to initialise");
}

}


Solution

  • You're using WideCharToMultiByte wrong. You need to pass it a string buffer to receive the converted string. Using NULL and 0 as parameters as you have done will return the required size of the result string.

    int length = WideCharToMultiByte (CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, NULL, 0,  NULL, NULL);
    std::string LogURL(length+1, 0);
    int result = WideCharToMultiByte (CP_ACP, WC_COMPOSITECHECK, wsURL.c_str(), -1, &LogURL[0], length+1,  NULL, NULL);
    

    You should check result for a non-zero value to make sure the function worked correctly.