使用WCHAR作为CHAR?

jma*_*erx 1 c c++

GDI +使用WCHAR而不是WinAPI允许的CHAR.通常我可以这样做:

char *str = "C:/x.bmp";
Run Code Online (Sandbox Code Playgroud)

但我如何为wchar做这个?我不能这么做

wchar_t *file = "C:/x.bmp";
Run Code Online (Sandbox Code Playgroud)

谢谢

Art*_*cto 8

wchar_t *file = L"C:/x.bmp";
Run Code Online (Sandbox Code Playgroud)

L引入了一个宽字符串.

在Windows中,习惯上使用根据某些预处理器定义而行为不同的宏.请参阅http://msdn.microsoft.com/en-us/library/c426s321(VS.71).aspx

你会写:

_TCHAR *file = _TEXT("C:/x.bmp");
Run Code Online (Sandbox Code Playgroud)


Kir*_*sky 6

const wchar_t *file = L"C:/x.bmp";
Run Code Online (Sandbox Code Playgroud)

这是根据C++标准2.13.4/1:

<...>以L开头的字符串文字,例如L"asdf",是一个宽字符串文字.宽字符串文字具有类型"n const wchar_t的数组"并具有静态存储持续时间,其中n是下面定义的字符串的大小,并使用给定的字符进行初始化.

请注意,您应该const在此处使用限定符.尝试修改字符串文字的效果未定义(2.13.4/2).

  • 为'const`-正确性+1.我讨厌忽视`const`的人.编译器指出愚蠢错误的能力被严重低估了. (2认同)