Domanda

Sto cercando di convertire una stringa char a una stringa WCHAR.

In dettaglio: sto cercando di convertire un char [] a un wchar [] prima e quindi aggiungere "1" per quella stringa e la stampa è

.
char src[256] = "c:\\user";

wchar_t temp_src[256];
mbtowc(temp_src, src, 256);

wchar_t path[256];

StringCbPrintf(path, 256, _T("%s 1"), temp_src);
wcout << path;

Ma esso stampa solo c

E 'questo il modo giusto per la conversione da char a wchar? Sono venuto a conoscenza di un altro modo allora. Ma mi piacerebbe sapere perché il codice precedente funziona il modo in cui funziona?

È stato utile?

Soluzione

mbtowc convertiti solo un singolo carattere. Cercavi di utilizzare mbstowcs ?

In genere si chiama questa funzione due volte; il primo ad ottenere la dimensione di buffer richiesto, e il secondo per effettivamente convertirlo:

#include <cstdlib> // for mbstowcs

const char* mbs = "c:\\user";
size_t requiredSize = ::mbstowcs(NULL, mbs, 0);
wchar_t* wcs = new wchar_t[requiredSize + 1];
if(::mbstowcs(wcs, mbs, requiredSize + 1) != (size_t)(-1))
{
    // Do what's needed with the wcs string
}
delete[] wcs;

Se si preferisce utilizzare mbstowcs_s (a causa del warning di deprecazione), poi fare questo:

#include <cstdlib> // also for mbstowcs_s

const char* mbs = "c:\\user";
size_t requiredSize = 0;
::mbstowcs_s(&requiredSize, NULL, 0, mbs, 0);
wchar_t* wcs = new wchar_t[requiredSize + 1];
::mbstowcs_s(&requiredSize, wcs, requiredSize + 1, mbs, requiredSize);
if(requiredSize != 0)
{
    // Do what's needed with the wcs string
}
delete[] wcs;

assicurarsi che si prende cura dei problemi di locale tramite setlocale () o utilizzando le versioni di mbstowcs() (come mbstowcs_l() o mbstowcs_s_l()) che accetta un argomento locale.

Altri suggerimenti

perché stai usando codice C, e perché non scrivere in modo più portatile, per esempio quello che vorrei fare qui è usare lo STL!

std::string  src = std::string("C:\\user") +
                   std::string(" 1");
std::wstring dne = std::wstring(src.begin(), src.end());

wcout << dne;

è così semplice è facile: D

L "Ciao Mondo"

il prefisso L davanti alla stringa rende una stringa char ampia.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top