How to convert wstring to LPOLESTR? - wstring

The below is the one that I have tried and it did not work.
std::wstring = L"Text";
USES_CONVERSION;
LPOLESTR lpDesc = W2OLE((LPWSTR)wsDescr.c_str());
Please any one cany say what is the better way to do?

LPOLESTR is a string of OLECHAR which is essentially wchar_t. So LPOLESTR is a null-terminated wchar_t*. LPOLESTR is a typedef created by Microsoft. These are vestiges of an automatic ANSI / Unicode conversion scheme that Microsoft used prior to MFC 4.0 and has since abandoned. For Win32 development, "OLE" corresponds to Unicode. For example, in Win32 development, an OLECHAR is simply a wchar_t and an LPOLESTR is a wide character string (e.g. wchar_t*).
To construct wstring from an array of wchar_t characters it is straight forward -
wchar_t* Array = L"Hello";
std::wstring strArray(Array);
to convert the other direction from wstring to wchar_t*, you can do this -
wstring wstr = L"Test wstring";
const wchar_t *pwstr = wstr.c_str();
you can also try this,
LPOLESTR tempString = W2OLE((wchar_t*)wstring_temp.c_str());

You need no conversion at all, just copy the string:
std::wstring str = L"Text";
LPOLESTR lpDesc = (LPOLESTR) new wchar_t[str.length() + 1];
strcpy(lpDesc, str.c_str());
delete[] lpDesc;

Related

How to convert double* data to const char* or QByteArray efficiently

I am trying to use the network programming APIs in Qt in my project. One part of my code requires me to convert double* data to QByteArray or a const char*.
I searched through the stackoverflow questions and could find many people suggesting this code :
QByteArray array(reinterpret_cast<const char*>(data), sizeof(double));
or, for an array of double :
QByteArray::fromRawData(reinterpret_cast<const char*>(data),s*sizeof(double));
When I use them in my function, It does notgive me the desired result. The output seems to be random characters.
Please Suggest an efficient way to implement it in Qt. Thank you very much for your time.
Regards
Alok
If you just need to encode and decode a double into a byte array, this works:
double value = 3.14159275;
// Encode the value into the byte array
QByteArray byteArray(reinterpret_cast<const char*>(&value), sizeof(double));
// Decode the value
double outValue;
// Copy the data from the byte array into the double
memcpy(&outValue, byteArray.data(), sizeof(double));
printf("%f", outValue);
However, that is not the best way to send data over the network, as it will depend on the platform specifics of how the machines encode the double type. I would recommend you look at the QDataStream class, which allows you to do this:
double value = 3.14159275;
// Encode the value into the byte array
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);
stream << value;
// Decode the value
double outValue;
QDataStream readStream(&byteArray, QIODevice::ReadOnly);
readStream >> outValue;
printf("%f", outValue);
This is now platform independent, and the stream operators make it very convenient and easy to read.
Assuming that you want to create a human readable string:
double d = 3.141459;
QString s = QString::number(d); // method has options for format and precision, see docs
or if you need localization where locale is a QLocale object:
s = locale.toString(d); // method has options for format and precision, see docs
You can easily convert the string into a QByteArray using s.toUtf8() or s.toLatin1() if really necessary. If speed is important there also is:
QByteArray ba = QByteArray::number(d); // method has options for format and precision, see docs

QString to unicode std::string

I know there is plenty of information about converting QString to char*, but I still need some clarification in this question.
Qt provides QTextCodecs to convert QString (which internally stores characters in unicode) to QByteArray, allowing me to retrieve char* which represents the string in some non-unicode encoding. But what should I do when I want to get a unicode QByteArray?
QTextCodec* codec = QTextCodec::codecForName("UTF-8");
QString qstr = codec->toUnicode("Юникод");
std::string stdstr(reinterpret_cast<const char*>(qstr.constData()), qstr.size() * 2 ); // * 2 since unicode character is twice longer than char
qDebug() << QString(reinterpret_cast<const QChar*>(stdstr.c_str()), stdstr.size() / 2); // same
The above code prints "Юникод" as I've expected. But I'd like to know if that is the right way to get to the unicode char* of the QString. In particular, reinterpret_casts and size arithmetics in this technique looks pretty ugly.
The below applies to Qt 5. Qt 4's behavior was different and, in practice, broken.
You need to choose:
Whether you want the 8-bit wide std::string or 16-bit wide std::wstring, or some other type.
What encoding is desired in your target string?
Internally, QString stores UTF-16 encoded data, so any Unicode code point may be represented in one or two QChars.
Common cases:
Locally encoded 8-bit std::string (as in: system locale):
std::string(str.toLocal8Bit().constData())
UTF-8 encoded 8-bit std::string:
str.toStdString()
This is equivalent to:
std::string(str.toUtf8().constData())
UTF-16 or UCS-4 encoded std::wstring, 16- or 32 bits wide, respectively. The selection of 16- vs. 32-bit encoding is done by Qt to match the platform's width of wchar_t.
str.toStdWString()
U16 or U32 strings of C++11 - from Qt 5.5 onwards:
str.toStdU16String()
str.toStdU32String()
UTF-16 encoded 16-bit std::u16string - this hack is only needed up to Qt 5.4:
std::u16string(reinterpret_cast<const char16_t*>(str.constData()))
This encoding does not include byte order marks (BOMs).
It's easy to prepend BOMs to the QString itself before converting it:
QString src = ...;
src.prepend(QChar::ByteOrderMark);
#if QT_VERSION < QT_VERSION_CHECK(5,5,0)
auto dst = std::u16string{reinterpret_cast<const char16_t*>(src.constData()),
src.size()};
#else
auto dst = src.toStdU16String();
If you expect the strings to be large, you can skip one copy:
const QString src = ...;
std::u16string dst;
dst.reserve(src.size() + 2); // BOM + termination
dst.append(char16_t(QChar::ByteOrderMark));
dst.append(reinterpret_cast<const char16_t*>(src.constData()),
src.size()+1);
In both cases, dst is now portable to systems with either endianness.
Use this:
QString Widen(const std::string &stdStr)
{
return QString::fromUtf8(stdStr.data(), stdStr.size());
}
std::string Narrow(const QString &qtStr)
{
QByteArray utf8 = qtStr.toUtf8();
return std::string(utf8.data(), utf8.size());
}
In all cases you should have utf8 in std::string.
You can get the QByteArray from a UTF-16 encoded QString using this:
QTextCodec *codec = QTextCodec::codecForName("UTF-16");
QTextEncoder *encoderWithoutBom = codec->makeEncoder( QTextCodec::IgnoreHeader );
QByteArray array = encoderWithoutBom->fromUnicode( str );
This way you ignore the unicode byte order mark (BOM) at the beginning.
You can convert it to char * like:
int dataSize=array.size();
char * data= new char[dataSize];
for(int i=0;i<dataSize;i++)
{
data[i]=array[i];
}
Or simply:
char *data = array.data();

Qt can't get characters from Unicode string

How can I get Unicode character (QChare type) from Unicode characters string (QString type).?I am trying with operator[] for Qstring object, and with it's member function at(), but it's not helping me(I'm using Qt Creator 2.0.1). I'm begginer in Qt, so this is maybe a simple question.
Did you try something like:
QString s("text");
QChar unicodeChar(s.at(0).unicode());
If you load your string into a QString, you can still use the .at(index) function. It will return a QChar which is a single wchar_t (UTF-16). You can cast that QChar to a wchar_t to get the unicode character.

what's the difference between QString and QLatin1String?

Like the title
1.what's the difference between QString and QLatin1String??
2.when and where do I need to use one of them??
3.following:
QString str;
str = "";
str = QLatin1String("");
Is "" == QLatin1String("")??
QString holds unicode. A string literal "foo" is a byte sequence that could contain text in any encoding. When assigning a string literal to a QString, QString str = "foo", you implicitely convert from a byte sequence in undefined encoding to a QString holding unicode. The QString(const char*) constructor assumes ASCII and will convert as if you typed QString str = QString::fromAscii("foo"). That would break if you use non-ascii literals in your source files (e.g., japanese string literals in UTF-8) or pass character data from a char* or QByteArray you read from elsewhere (a file, socket, etc.). Thus it's good practice to keep the unicode QString world and the byte array QByteArray/char* world separated and only convert between those two explicitly, clearly stating which encoding you want to use to convert between those two. One can define QT_NO_CAST_FROM_ASCII and QT_NO_CAST_TO_ASCII to enforce explicit conversions (I would always enable them when writing a parser of any sort).
Now, to assign a latin1 string literal to a QString variable using explicit conversion, one can use
QString foo = QString::fromLatin1("föö");
or
QString foo = QLatin1String("föö");
Both state that the literal is encoded in latin1 and allow "encoding-safe" conversions to unicode.
I find QLatin1String nicer to read and the QLatin1String docs explain why it will be also faster in some situations.
Wrapping string literals, or in some cases QByteArray or char* variables, holding latin1 data for conversion is the main use for QLatin1String, one wouldn't use QLatin1String as method arguments, member variables or temporaries (all QString).
QString is Unicode based while QLatin1String is US-ASCII/Latin-1 based
Unicode is a super set of US-ASCII/Latin-1. If you only deal with US-ASCII/Latin-1 characters, the two are the same for you.
http://doc.qt.io/qt-4.8/qstring.html
http://doc.qt.io/qt-4.8/qlatin1string.html

How to append this in Qt?

I want to add a new line in this. This is my sample code:
ui->button->setText(" Tips " + "\n" + TipsCount );
This is the error it shows:
invalid operands of types 'const char [7]' and 'const char [2]' to binary 'operator+'
But when I add to label it gets appended!
ui->label->setText(name + "\n" + City );
Can someone please help me?
This is a very common problem in C++ (in general, not just QT).
Thanks to the magic of operator overloading, name + "\n" gets turned into a method call (couldn't say which one since you don't list the type). In other words, because one of the two things is an object with + overloaded it works.
However when you try to do "abc" + "de", it blows up. The reason is because the compiler attempts to add two arrays together. It doesn't understand that you mean concatenation, and tries to treat it as an arithmetic operation.
To correct this, wrap your string literals in the appropriate string object type (std::string or QString most likely).
Here is a little case study:
QString h = "Hello"; // works
QString w = "World"; // works too, of course
QString a = h + "World"; // works
QString b = "Hello" + w; // also works
QString c = "Hello" + "World"; // does not work
String literals in C++ (text in quotes) are not objects and don't have methods...just like numeric values aren't objects. To make a string start acting "object-like" it has to get wrapped up into an object. QString is one of those wrapping objects, as is the std::string in C++.
Yet the behavior you see in a and b show we're somehow able to add a string literal to an object. That comes from the fact that Qt has defined global operator overloads for both the case where the left operand is a QString with the right a const char*:
http://doc.qt.nokia.com/latest/qstring.html#operator-2b-24
...as well as the other case where the left is a const char* and the right is a QString:
http://doc.qt.nokia.com/latest/qstring.html#operator-2b-27
If those did not exist then you would have had to write:
QString a = h + QString("World");
QString b = QString("Hello") + w;
You could still do that if you want. In that case what you'll cause to run will be the addition overload for both operands as QString:
http://doc.qt.nokia.com/latest/qstring.html#operator-2b-24
But if even that didn't exist, you'd have to call a member function. For instance, append():
http://doc.qt.nokia.com/latest/qstring.html#append
In fact, you might notice that there's no overload for appending an integer to a string. (There's one for a char, however.) So if your TipsCount is an integer, you'll have to find some way of turning it into a QString. The static number() methods are one way.
http://doc.qt.nokia.com/latest/qstring.html#number
So you might find you need:
ui->button->setText(QString(" Tips ") + "\n" + QString::number(TipsCount));

Resources