質問

私はクラスを変更してstd :: stringを使用しました(私が得た答えに基づいて ここ しかし、私が持っている関数wchar_t *を返します。 std :: stringに変換するにはどうすればよいですか?

私はこれを試しました:

std::string test = args.OptionArg();

しかし、エラーC2440:「初期化」:「wchar_t *」から 'std :: basic_string <_elem、_traits、_ax>'に変換することはできません。

役に立ちましたか?

解決

使用することができます wstring すべてをUnicodeに保ちます

他のヒント

wstring ws( args.OptionArg() );
string test( ws.begin(), ws.end() );

次の関数を使用して、幅広の文字列をASCII文字列に変換できます。

#include <locale>
#include <sstream>
#include <string>

std::string ToNarrow( const wchar_t *s, char dfault = '?', 
                      const std::locale& loc = std::locale() )
{
  std::ostringstream stm;

  while( *s != L'\0' ) {
    stm << std::use_facet< std::ctype<wchar_t> >( loc ).narrow( *s++, dfault );
  }
  return stm.str();
}

これは、同等のASCII文字が存在しない幅広いキャラクターを置き換えるだけであることに注意してください。 dfault パラメーター; UTF-16からUTF-8に変換されません。 UTF-8に変換する場合は、次のようなライブラリを使用します ICU.

これは古い質問ですが、それが実際にコンバージョンを求めているのではなく、MircosoftのTcharのものを使用してASCIIとUnicodeの両方を構築できるようにする場合は、STD :: Stringが本当にあることを思い出すことができます

typedef std::basic_string<char> string

したがって、たとえば、私たち自身のTypedefを定義することができます

#include <string>
namespace magic {
typedef std::basic_string<TCHAR> string;
}

その後、使用できます magic::stringTCHAR, LPCTSTR, 、など

ただ楽しみのために:-):

const wchar_t* val = L"hello mfc";
std::string test((LPCTSTR)CString(val));

次のコードはより簡潔になります:

wchar_t wstr[500];
char string[500];
sprintf(string,"%ls",wstr);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top