简体   繁体   中英

How to convert std::string to QString preserving values and vice versa?

I am dealing with std::strings, in low level processing so I have to manipulate bits of characters of that string.
Also I have to show the results using GUI by viewing the result on QPlainTextEdit, as they may be copied for reverse processing.
so I deal with strings and results like 0xe3 may occur. and when I convert the std::string to QString to be shown in the GUI and vice versa. I use,

 QString::fromStdString(myString); // to convert std::string to QString
 myQString.toStdString();          // to convert back from QString to std::string

The problem is that when values result from processing on the string. after converting it to QString and try to convert it back, values change.
I mean the value of each character,for example

0x3f becomes 0xbd, and 0xe3 becomes 0xef

I guess the problem happens due to encoding issues between std::string and QString, but I can not figure out how to deal with it or how to get the right values from QString.

The source string is not valid UTF-8 and thus the roundtrip fails because the toStdString and fromStdString methods assume UTF-8. The Latin-1 roundtrip shouldn't fail and should simply map bytes 0-255 to Unicode C0 and C1. The code is a bit more verbose:

void test(const std::string & input) {
  auto latin_input = QByteArray::fromStdString(input);
  auto string = QString::fromLatin1(latin_input);
  auto latin_output = string.toLatin1();
  Q_ASSERT(latin_input == latin_output);
  auto output = latin_output.toStdString();
  Q_ASSERT(input == output);
}

Note that many of the Latin-1 characters are not printable, so the QPlainTextEdit will not display them! To fix that, you'd need to create a custom translation table that provides a printable equivalent for every character code between 0 and 255.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM