C++ 将窄字符串转换为宽字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6691555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:32:43  来源:igfitidea点击:

converting narrow string to wide string

c++stringvisual-c++unicode

提问by saplingPro

How can i convert a narrow stringto a wide string?

如何将窄转换string为宽string

I have tried this method :

我试过这种方法:

string myName;
getline( cin , myName );
wstring printerName( L(myName) );  // error C3861: 'L': identifier not found
wchar_t* WprinterName = printerName.c_str(); // error C2440: 'initializing' : cannot convert from 'const wchar_t *' to 'wchar_t *'

But i get errors as listed above.

但是我得到了上面列出的错误。

Why do i get these errors ? How can i fix them ?

为什么我会收到这些错误?我该如何修复它们?

Is there any other method of directly converting a narrowstring to a widestring ?

有没有其他方法可以直接将narrow字符串转换为wide字符串?

回答by Blazes

If the source is ASCII encoded, you can just do this:

如果源是 ASCII 编码的,你可以这样做:

wstring printerName;
printerName.assign( myName.begin(), myName.end() );

回答by Christopher

You should do this :

你应该做这个 :

inline std::wstring convert( const std::string& as )
{
            // deal with trivial case of empty string
    if( as.empty() )    return std::wstring();

            // determine required length of new string
    size_t reqLength = ::MultiByteToWideChar( CP_UTF8, 0, as.c_str(), (int)as.length(), 0, 0 );

            // construct new string of required length
    std::wstring ret( reqLength, L'
inline std::wstring convert( const std::string& as )
{
    wchar_t* buf = new wchar_t[as.size() * 2 + 2];
    swprintf( buf, L"%S", as.c_str() );
    std::wstring rval = buf;
    delete[] buf;
    return rval;
}
' ); // convert old string to new string ::MultiByteToWideChar( CP_UTF8, 0, as.c_str(), (int)as.length(), &ret[0], (int)ret.length() ); // return new string ( compiler should optimize this away ) return ret; }

This expects the std::string to be UTF-8 (CP_UTF8), when you have another encoding replace the codepage.

这期望 std::string 为 UTF-8 ( CP_UTF8),当您有另一种编码替换代码页时。

Another way could be :

另一种方法可能是:

std::string str = "Hello";
std::wstring str2(str.length(), L' '); // Make room for characters

// Copy string to wstring.
std::copy(str.begin(), str.end(), str2.begin());

回答by ólafur Waage

I found thiswhile googling the problem. I have pasted the code for reference. Author of this post is Paul McKenzie.

我在谷歌搜索问题时发现了这一点。我已经粘贴了代码以供参考。这篇文章的作者是保罗·麦肯齐。

#include <atlbase.h>

std::wstring wideString(L"My wide string");
std::string narrowString("My not-so-wide string");

ATL::CW2A narrow(wideString.c_str()); // narrow is a narrow string
ATL::CA2W wide(asciiString.c_str()); // wide is a wide string

回答by Alex

ATL (non-express editions of Visual Studio) has a couple useful class types which can convert the strings plainly. You can use the constructor directly, if you do not need to hold onto the string.

ATL(Visual Studio 的非快速版本)有几个有用的类类型,可以简单地转换字符串。如果不需要保留字符串,则可以直接使用构造函数。

errno_t wcstombs_s(
   size_t *pReturnValue,
   char *mbstr,
   size_t sizeInBytes,
   const wchar_t *wcstr,
   size_t count 
);

errno_t mbstowcs_s(
   size_t *pReturnValue,
   wchar_t *wcstr,
   size_t sizeInWords,
   const char *mbstr,
   size_t count 

回答by eddyq

Here are two functions that can be used: mbstowcs_s and wcstombs_s.

这里有两个可以使用的函数:mbstowcs_s 和 wcstombs_s。

mbstowcs_s: Converts a sequence of multibyte characters to a corresponding sequence of wide characters. wcstombs_s: Converts a sequence of wide characters to a corresponding sequence of multibyte characters.

mbstowcs_s:将多字节字符序列转换为相应的宽字符序列。wcstombs_s:将宽字符序列转换为相应的多字节字符序列。

    // wchar_t* wstr = L"A wide string";     // Error: cannot convert from 'const wchar_t *' to 'wchar_t *'

wchar_t const* wstr = L"A wide string";             // okay
const wchar_t* wstr_equivalent = L"A wide string";  // also okay

);

);

See http://msdn.microsoft.com/en-us/library/eyktyxsx.aspxand http://msdn.microsoft.com/en-us/library/s7wzt4be.aspx.

请参阅http://msdn.microsoft.com/en-us/library/eyktyxsx.aspxhttp://msdn.microsoft.com/en-us/library/s7wzt4be.aspx

回答by Indinfer

The original question of this thread was: "How can i convert a narrow string to a wide string?"

该线程的原始问题是:“如何将窄字符串转换为宽字符串?”

However, from the example code given in the question, there seems to be no conversion necessary. Rather, there is a compiler error due to the newer compilers deprecating something that used to be okay. Here is what I think is going on:

但是,从问题中给出的示例代码来看,似乎没有必要进行转换。相反,由于较新的编译器弃用了曾经没问题的东西,因此存在编译器错误。这是我认为正在发生的事情:

string myName;
wchar_t wstr[BUFFER_SIZE];

getline( cin , myName );
mbtowc(wstr, myName, BUFFER_SIZE);

The c_str() seems to be treated the same as a literal, and is considered a constant (const). You could use a cast. But preferable is to add const.

c_str() 似乎被视为与文字相同,并被视为常量 (const)。你可以使用演员表。但最好是添加const。

The best answer I have seen for converting between wide and narrow strings is to use std::wstringstream. And this is one of the answers given to C++ Convert string (or char*) to wstring (or wchar_t*)

我见过的在宽字符串和窄字符串之间转换的最佳答案是使用 std::wstringstream。这是C++ Convert string (or char*) to wstring (or wchar_t*)的答案之一

You can convert most anything to and from strings and wide strings using stringstream and wstringstream.

您可以使用 stringstream 和 wstringstream 将大多数内容与字符串和宽字符串相互转换。

回答by ravenspoint

The Windows API provides routines for doing this: WideCharToMultiByte() and MultiByteToWideChar(). However, they are a pain to use. Each conversion requires two calls to the routines and you have to look after allocating/freeing memory and making sure the strings are correctly terminated. You need a wrapper!

Windows API 提供了执行此操作的例程:WideCharToMultiByte() 和 MultiByteToWideChar()。但是,它们使用起来很痛苦。每次转换都需要对例程进行两次调用,您必须注意分配/释放内存并确保字符串正确终止。你需要一个包装!

I have a convenient C++ wrapper on my blog, here, which you are welcome to use.

我的博客上有一个方便的 C++ 包装器,这里,欢迎您使用。

回答by Mr.C64

This articlepublished on the MSDN Magazine 2016 September issue discusses the conversion in details using Win32 APIs.

发表在 MSDN 杂志 2016 年 9 月号上的这篇文章详细讨论了使用 Win32 API 的转换。

Note that using MultiByteToWideChar()is much fasterthan using the std:: stuff on Windows.

请注意,使用MultiByteToWideChar()要快得多比在Windows上使用的std ::东西。

回答by Simon Rigét

Use mbtowc():

使用mbtowc():

##代码##