QString shows garbage characeter
-
Hi All,
I am reading the following text from the text file and setText that string to label i am reading the text into QString and after reading i am setting the text. It is showing garbage character after applying the setText.
Below is my code.
@QFile file("C:/Users/my/Desktop/Issues.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } QString line(file.readLine()); label->setText(line); file.close();@###############################
Below is the file content.TEMP (°C)
###############################But the same code if i do label->setText("TEMP (°C)") then is working fine.
Output of the above code is garbage character when we read the content from file ?
Here ° (celcius) character is displayed but garbage character will come. Is there any reason why garbage character is coming when we reading the this special character (not entered through keypad) ?Thanks,
Neel -
It's very likely that this is because of the file encoding. Maybe the file content is not encdoded in ASCII but in UTF-8 or some other encoding.
Maybe it is sufficient to call "QString::toAscii()":http://doc-snapshot.qt-project.org/4.8/qstring.html#toAscii to convert the QString to a usable format.
-
If that's not going to do the trick try using "QTextStream":http://qt-project.org/doc/qt-4.8/qtextstream.html for reading and set the appropriate text codec.
-
Now it is showing the correct string. But following is my observation.
when i write the below code then characters are displaying garbage and when i comment below code then characters are displaying correctly.
@QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForCStrings(codec);
QTextCodec::setCodecForTr(codec);@Can you please tell me why this strange behaviour happens ?
-
I got the issue. One application written the file in ANSI format that is why it is not able to decode it.
Anyway thanks for your support.One more thing i want to know is if i already had applied codec for UTF-8 and if i want to apply the codec for another ISO then can i apply two times after one already set ?
@
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForCStrings(codec);
QTextCodec::setCodecForTr(codec);
@after above code i want to apply same with ISO type. can i set ? i am not able to set ? How to do that ?