gpt4 book ai didi

windows - 使用 MultiByteToWideChar

转载 作者:可可西里 更新时间:2023-11-01 10:27:27 25 4
gpt4 key购买 nike

以下代码打印了所需的输出,但它在字符串末尾打印了乱码。最后一次调用 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);
}

最佳答案

关于 cbMultiByte 参数,MSDN 是这样说的:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com