简体   繁体   English

WriteConsole() 奇怪的字符?

[英]WriteConsole() weird characters?

I use this snippet to create a console from inside a dll.我使用此代码段从 dll 内部创建控制台。 That dll gets loaded in a game.该 dll 被加载到游戏中。

CODE SNIPPET代码片段

The console window creates fine.控制台窗口创建得很好。 But when i write stuff to it, i just get stuff like "???D??".但是当我给它写东西时,我只会得到像“???D??”这样的东西。

I know i have to use the printf() syntax.我知道我必须使用 printf() 语法。 So i use所以我用

wprintf("%s", "test");

Any pointers?任何指针?

Try using:尝试使用:

wprintf(L"%s", "test");

as wprintf takes an wide character string as input因为 wprintf 需要一个宽字符串作为输入

Edit : Based on the fact that the behaviour of %s and %S changes when used in wprintf what about:编辑:基于在 wprintf 中使用时 %s 和 %S 的行为会发生变化的事实:

wprintf("%s", L"test");

The %s in wprintf expects a wide character string this L"test" is. wprintf 中的 %s 需要一个宽字符串,这个 L"test" 是。
I removed the "L" on the format parameter since wprintf is defined as:我删除了格式参数上的“L”,因为 wprintf 被定义为:

int wprintf(char *fmt, ...)

You're calling wprintf(), the "wide-character" version of the printf() routine.您正在调用 wprintf(),这是 printf() 例程的“宽字符”版本。 There's one nasty catch with these "wide-character" functions, in that the meaning of "%s" changes:这些“宽字符”函数有一个令人讨厌的问题,因为“%s”的含义发生了变化:

printf() - "%s" means argument is a normal string, "%S" means it's a wide-character string printf() - "%s" 表示参数是一个普通字符串,"%S" 表示它是一个宽字符串

wprintf() - "%s" means argument is a wide-character string, "%S" means it's a normal string wprintf() - "%s" 表示参数是一个宽字符串,"%S" 表示它是一个普通字符串

So your call to wprintf() is telling it that the argument is a wide-character string, but it's not: change it to所以你对 wprintf() 的调用是告诉它参数是一个宽字符串,但它不是:将其更改为

printf("%s", "test");

A good habit is to use portability macro _T() which does nothing when we use ASCII and prepends all strings with L when UNICODE is defined.一个好习惯是使用可移植性宏 _T() ,当我们使用 ASCII 时它什么也不做,并且在定义 UNICODE 时在所有字符串前加上 L。 And using _t prepended functions which are really just macros that map to plain functions when we use ASCII and map to w prepended functions when UNICODE is defined.并使用 _t 前置函数,它们实际上只是在我们使用 ASCII 时映射到普通函数的宏,并在定义 UNICODE 时映射到 w 前置函数。 That way you always have a portable code - which works in both versions:这样你总是有一个可移植的代码 - 它适用于两个版本:

_tprintf(_T("%s"),_T("test");

the "%s" format string tells wprintf it should interpret the first argument as a wide character string. "%s" 格式字符串告诉 wprintf 它应该将第一个参数解释为宽字符串。

To avoid these mixed-encoding problems, you can use the TCHAR macro's:为了避免这些混合编码问题,您可以使用 TCHAR 宏:

LPCTSTR pName = _T("World");
_tprintf( _T("%s, %s"), _T("Hello"), pName );

Your encoding is wrong, as you are using wstring characters, but probably only have an ascii console.您的编码错误,因为您使用的是 wstring 字符,但可能只有一个 ascii 控制台。 Make sure that you are using a unicode font in your console.确保您在控制台中使用 unicode 字体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM