LPCSTR 类型字符串出现乱码或显示错误

The LPCSTR type string is garbled or displayed error

本文关键字:显示 错误 类型 字符串 LPCSTR      更新时间:2023-10-16

我有一个LPCSTR,我想转换为std::stringchar*

LPCSTR strName;
_tprintf(_T("%sn"), strName);

我正在尝试获取计算机上的所有音频设备并显示,但是要获得LPCSTR类型的直接输出是乱码,请使用上面的代码输出正确的结果。

有没有办法保存正确的输出?

以下是完整的代码:

Add a dependency to the property:
comctl32.lib;winmm.lib;dsound.lib;dxguid.lib;odbc32.lib;odbccp32.lib

ListSoundDev.h

#ifndef _LISTSOUNDDEV_HEAD_
#define _LISTSOUNDDEV_HEAD_
#include<tchar.h>
#include <dshow.h>
#include<iostream>
#include<vector>
#include<mmsystem.h>
#include<mmreg.h>
#include<dsound.h>
#pragma comment(lib, "strmiids.lib")
#pragma comment(lib, "Quartz.lib")
#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "dsound.lib")
#pragma comment(lib, "dxguid.lib")
#pragma comment(lib, "strmiids")
using namespace std;
typedef struct _DevItem
{
LPCSTR strName;
GUID guid;
} DevItem;
#endif

主.cpp

#include"ListSoundDev_head.h"
std::vector<DevItem>    m_CapDevices;
BOOL CALLBACK DSEnumCallback(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext)
{
std::vector<DevItem> *pLst = (std::vector<DevItem> *) lpContext;
if (pLst)
{
DevItem item;
memset(&item, 0, sizeof(item));
item.strName = lpcstrDescription;
if (lpGuid)
item.guid = *lpGuid;
else
item.guid = GUID_NULL;
pLst->push_back(item);
return TRUE;
}
return FALSE;
}
int main()
{
std::vector<DevItem>::iterator it;
HRESULT hr = S_OK;
setlocale(LC_ALL, "chs");
hr = DirectSoundCaptureEnumerate((LPDSENUMCALLBACKW)DSEnumCallback, (LPVOID)&m_CapDevices);
for (it = m_CapDevices.begin(); it != m_CapDevices.end(); it++){
_tprintf(_T("%sn"), it->strName);//output correct
printf("%sn",it->strName);//output error
std::cout << it->strName << std::endl;//output error
}
}

预期产出:

麦克风 (Realtek High Definition Au

实际输出:

肯琴螛

预期产出:

瑞昱数字输入(瑞昱

实际输出:

R

如何使printf()std::cout可以直接输出正确的结果?

非常感谢您的回答,我已经解决了这个问题。

解决方案是使用以下代码进行转换。

字符集为 Unicode。

char newStr[100];
wcstombs(newStr, (wchar_t*)it->strName, 100);
printf("newStr=%sn", newStr);

字符集为多字节

printf("%sn", it->strName);

但是,当我在C++控制台中编写此程序以获取麦克风的音频设备名称时(Realtek High Definition Au,但在MFC中使用此代码获取麦克风的设备名称(Realtek High Definition Audio)是什么原因?