2016-08-19 118 views
-3

我有问题,使这个小片代码工作:C++编程转换为const char *为const wchart_t *

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

using namespace std; 

string Filepath; 

string Temp; 

int WINAPI WinMain(HINSTANCE instanceHandle, HINSTANCE, char*, int) 
{ 
    const char* env_p = std::getenv("TEMP"); 
    std::getenv("TEMP"); 
    Temp = env_p; 
    Filepath = Temp + "\\File.txt"; 


Editfile id(Filepath.c_str()); 
    std::cin.get(); 
    return 0; 
} 

错误C2664从 “为const char *” 转换为 “常量为wchar_t *” 是不可能的

我看到了问题,但对我来说修复它并不容易。

+0

那一行究竟你得到这个错误?你可以使用[MultiByteToWideChar函数](https://msdn.microsoft.com/en-us/library/windows/desktop/dd319072(v = vs.85).aspx),但也许你不需要它。这取决于你的项目设置。你可能只需要对你使用的API进行调整 – mvidelgauz

+0

'std :: getenv()'可以返回一个'nullptr'。你可以使用:'Temp = env_p? env_p:“”;'以避免未定义的行为。 – Galik

+0

Editfile id(Filepath.c_str()); – Marabunta

回答

0

charstd::getenv这样的基础功能可以返回Windows中不可用的数据,因为Windows中的标准窄编码非常有限。

取而代之的是使用宽字符功能,对于环境的东西,最好是Windows API本身。

那么就没有必要编码之间进行转换,因为它的所有UTF-16,表示为C++ wchar_t基于字符串:

#include <string> 
#include <stdexcept>  // runtime error 
using namespace std; 

#undef UNICODE 
#define UNICODE 
#undef NOMINMAX 
#define NOMINMAX 
#undef STRICT 
#define STRICT 
#include <windows.h> 

auto hopefully(bool const e) -> bool { return e; } 
[[noreturn]] auto fail(string const& s) -> bool { throw runtime_error(s); } 

auto path_to_tempdir() 
    -> wstring 
{ 
    wstring result(MAX_PATH, L'#'); 

    DWORD const n = GetTempPath(result.size(), &result[0]); 
    hopefully(0 < n && n < result.size()) 
     || fail("GetTempPath failed"); 
    result.resize(n); 
    return result; 
} 

auto main() 
    -> int 
{ 
    // Just crash if there's no temp directory. 
    DWORD const as_infobox = MB_ICONINFORMATION | MB_SETFOREGROUND; 
    MessageBox(0, path_to_tempdir().c_str(), L"Temp directory:", as_infobox); 
} 
相关问题