windows - 使用 MultiByteToWideChar

标签 windows winapi

以下代码打印所需的输出,但在字符串末尾打印垃圾。最后一次调用 MultiByteToWideChar 有问题,但我不知道是什么问题。请帮忙??

#include "stdafx.h"
#include<Windows.h>
#include <iostream>
using namespace std;
#include<tchar.h>

int main( int, char *[] )
{
    TCHAR szPath[MAX_PATH];
    if(!GetModuleFileName(NULL,szPath,MAX_PATH))
    {cout<<"Unable to get module path"; exit(0);}

    char ansiStr[MAX_PATH];
    if(!WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,szPath,-1,
        ansiStr,MAX_PATH,NULL,NULL))
    {cout<<"Unicode to ANSI failed\n";
    cout<<GetLastError();exit(1);}

    string s(ansiStr);

    size_t pos = 0;

    while(1)
    {
        pos = s.find('\\',pos);
        if(pos == string::npos)
            break;
        s.insert(pos,1,'\\');
        pos+=2;
    }

    if(!MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,s.c_str(),s.size(),szPath,MAX_PATH))
    {cout<<"ANSI to Unicode failed"; exit(2);}

    wprintf(L"%s",szPath);
}

最佳答案

MSDN 对 cbMultiByte 参数有这样的说法:

If this parameter is -1, the function processes the entire input string, including the terminating null character. Therefore, the resulting Unicode string has a terminating null character, and the length returned by the function includes this character.

If this parameter is set to a positive integer, the function processes exactly the specified number of bytes. If the provided size does not include a terminating null character, the resulting Unicode string is not null-terminated, and the returned length does not include this character.

..因此,如果您希望输出字符串以 0 结尾,则应在传入的长度中包含 0 终止符,或者根据返回值自行终止 0...

关于windows - 使用 MultiByteToWideChar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10790632/

相关文章:

firefox - 除非窗口处于事件状态,否则 Selenium IDE 焦点事件不会触发

c++ - 如何使用 win32 CreateProcess 函数等到 child 完成写入文件

c++ - 异步控制台输出

c++ - 对于不同的操作系统,如何获取每个磁盘的回收站路径?

windows - 用于检查系统中是否存在 Java 主目录并检查 Java 版本的批处理脚本

c++ - 为什么将 ReadProcessMemory() 与当前进程的句柄一起使用?

c++ - 保护内容文件

c# - 为什么另一个应用程序窗口标题中的文本不正确?

php - 如何在 WampServer 中将 PHP 5.5.12 升级到 5.6.12

c++ - 如何获取安装在 Windows 7 中的主题列表(主题名称)?