2016-08-19 19 views
-3

私は、コードの仕事のこの小さな作品を作るために問題を抱えている:に "のconstのchar *" からの変換C++プログラミングのconst wchart_tへのconstのchar *に変換*

#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 wchar_t型は、*" ことはできません

私は問題を見るが、それを修正するのは簡単ではない。

+0

まさにこのエラーが発生した何行目では?あなたは[MultiByteToWideChar関数](https://msdn.microsoft.com/en-us/library/windows/desktop/dd319072(v = vs.85).aspx)を使っていますが、おそらくそれは必要ありません。プロジェクトの設定によって異なります。 – mvidelgauz

+0

'std :: getenv()'が 'nullptr'を返すことができるAPIを割り当てるだけでよいでしょう。あなたは 'Temp = env_p? env_p: ""; '定義されていない動作を避けるためです。 – Galik

+0

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

答えて

0

charstd::getenvなどの関数は、Windowsで標準の狭いエンコーディングが非常に制限されているため、Windowsで使用できないデータを返すことがあります。

代わりに、ワイド文字の関数を使用し、環境にはWindows API自体を使用することをお勧めします。それはC++でwchar_t基づいて文字列として表され、すべてのUTF-16ですので、

は、その後のエンコーディング間の変換する必要は、ありません。

#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); 
} 
関連する問題