Как перевести qstring в char
Converting QString to char* [duplicate]
I have a function (fopen in STL) that gives a char* argument as a path in my computer, but I must use QString in that place so it doesn’t work.
How can I convert QString to char* to solve this problem?
2 Answers 2
In order to convert a QString to a char*, then you first need to get a latin1 representation of the string by calling toLatin1() on it which will return a QByteArray. Then call data() on the QByteArray to get a pointer to the data stored in the byte array. See the documentation:
See the following example for a demonstration:
Note that it is necessary to store the bytearray before you call data() on it, a call like the following
will make the application crash as the QByteArray has not been stored and hence no longer exists
To convert a char* to a QString you can use the QString constructor that takes a QLatin1String, e.g:
See the documentation:
Of course, I discovered there is another way from this previous SO answer:
You could use QFile rather than std::fstream.
Alternatively convert the QString into a char* as follows:
The QString is in UTF-16 so it is converted toLatin1() here but QString has a couple of different conversions including toUtf8() (check your file-system it may use UTF-8).
As noted by @0A0D above: don’t store the char* in a variable without also getting a local copy of the QByteArray.
This is because toLatin1() returns an object of QByteArray. As it is not actually bound to a variable it is a temporary that is destroyed at the end of the expression. Thus the call to data() here returns a pointer to an internal structure that no longer exists after the ‘;’.
QString to char* conversion
I was trying to convert a QString to char* type by the following methods, but they don’t seem to work.
Can you elaborate the possible flaw with this method, or give an alternative method?
10 Answers 10
So perhaps you’re having other problems. How exactly doesn’t this work?
or safer, as Federico points out:
It’s far from optimal, but will do the work.
David’s answer works fine if you’re only using it for outputting to a file or displaying on the screen, but if a function or library requires a char* for parsing, then this method works best:
EDITED
this way also works
Your string may contain non Latin1 characters, which leads to undefined data. It depends of what you mean by «it deosn’t seem to work».
the Correct Solution Would be like this
Qt provides the simplest API
If you want non-const data pointer use
It is a viable way to use std::vector as an intermediate container:
Not the answer you’re looking for? Browse other questions tagged c++ qt qstring qtcore or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.22.41046
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Как перевести qstring в char
[quote author=»Thanatos.jsse» date=»1301106274″]You can do this:
@QString myString = «BlaBla»
char* myChar = myString.toStdString().c_str();@
[/quote]
Take care of the lifetime of these variables!
if you have an in parameter, you can do such things, although I would not got the way with std::string:
@
void foo(const char*);
It’s up to you, which encoding you use.
But all these functions return temporary objects, and calling constData returns the buffer of the temp objects. In the next line of code (when foo() returns) the temp object is destroyed and the buffer gets invalid!
So there is no way.
Luckily there is good old std c++ :
string appName = m_sAppName.toStdString();
Why should the be no way? I showed you some.
it is, but which format do you need?
all are const char* formats.
QString is unicode.
in general, it is possible:
@
QString text;
std::string s = text.toLatin1().constData;
foo(s.c_str());
@
If you really need a const char* I would convert it to and std::string (but reagrd the conversion!) and use the std::string. Who shall otherwise handle the memory? who shall allocate it? who shall free it?
you can also do the following:
Take care that text.length() might not valid if you then convert to utf8!
I said there is no way because you said the const char * is lost immediatly at the next line of code.
But I found a way using usual c++, as edited in my previous post.
if you use toStdString, take care of the encoding.
QString is unicode. So That is why I’ve written the stuff of the encoding.
[quote author=»Gerolf» date=»1301125342″]
Take care of the lifetime of these variables![/quote]
Ok Gerolf, I’ll take care in the following contributions.
thank you sir it was helpful
is there any way to do conversion of Qbytearray to QString
A QByteArray is not much more than a nice wrapper around a char*, so the same rules apply.
If you say that you get an error and you want help on that error, it is best to actually mention said error.
QString Constructor No 9 (which takes a QByteArray) uses UTF-8, so you need to ensure that your byte array uses that encoding. It is better to use QString’s static methods fromLatin1, fromLocal8Bit and fromUtf8 IMO because they are more explicit.
You can check «the documentation»:http://qt-project.org/doc/qt-5.0/qtcore/qstring.html for more detailed explanation.
And I’d also like to recommend some «good reading on character encoding»:http://www.joelonsoftware.com/articles/Unicode.html if you’re not already familiar with its concept.
This can be used for eg. to send debugging information from your GUI to the console; since Debug requires a const char * :
Проблема с Qt4: перевести QString в char и обратно
6 ответов
Помочь может макрос:
#define PCHQSTRING( ba, str, p ) \
QByteArray ba = str.toAscii(); \
p = ba.data();
Ниже приведен пример использования:
void func()
<
const char* cConType;
PCHQSTRING( v1, ctComboBox->currentText(), cConType );
const char* cUserName;
PCHQSTRING( v2, unLineEdit->text(), cUserName );
>
Вот две процедуры. Это для тех у кого ОСОБЫЕ проблемы с кодировками:
Хотя работать должны у всех.
void MY_QStringtochar(QString *str,char* qwe)<
char w;
unsigned short s[150];
QString::iterator p;
p=str->begin();
for (int i=0;i size();i++) <
unsigned short j=s;
switch(j)<
case 1040 : w=’А’; break;
case 1041 : w=’Б’; break;
case 1042 : w=’В’; break;
case 1043 : w=’Г’; break;
case 1044 : w=’Д’; break;
case 1045 : w=’Е’; break;
case 1046 : w=’Ж’; break;
case 1047 : w=’З’; break;
case 1048 : w=’И’; break;
case 1049 : w=’Й’; break;
case 1050 : w=’К’; break;
case 1051 : w=’Л’; break;
case 1052 : w=’М’; break;
case 1053 : w=’Н’; break;
case 1054 : w=’О’; break;
case 1055 : w=’П’; break;
case 1056 : w=’Р’; break;
case 1057 : w=’С’; break;
case 1058 : w=’Т’; break;
case 1059 : w=’У’; break;
case 1060 : w=’Ф’; break;
case 1061 : w=’Х’; break;
case 1062 : w=’Ц’; break;
case 1063 : w=’Ч’; break;
case 1064 : w=’Ш’; break;
case 1065 : w=’Щ’; break;
case 1066 : w=’Ъ’; break;
case 1067 : w=’Ы’; break;
case 1068 : w=’Ь’; break;
case 1069 : w=’Э’; break;
case 1070 : w=’Ю’; break;
case 1071 : w=’Я’; break;
case 1072 : w=’а’; break;
case 1073 : w=’б’; break;
case 1074 : w=’в’; break;
case 1075 : w=’г’; break;
case 1076 : w=’д’; break;
case 1077 : w=’е’; break;
case 1078 : w=’ж’; break;
case 1079 : w=’з’; break;
case 1080 : w=’и’; break;
case 1081 : w=’й’; break;
case 1082 : w=’к’; break;
case 1083 : w=’л’; break;
case 1084 : w=’м’; break;
case 1085 : w=’н’; break;
case 1086 : w=’о’; break;
case 1087 : w=’п’; break;
case 1088 : w=’р’; break;
case 1089 : w=’с’; break;
case 1090 : w=’т’; break;
case 1091 : w=’у’; break;
case 1092 : w=’ф’; break;
case 1093 : w=’х’; break;
case 1094 : w=’ц’; break;
case 1095 : w=’ч’; break;
case 1096 : w=’ш’; break;
case 1097 : w=’щ’; break;
case 1098 : w=’ъ’; break;
case 1100 : w=’ь’; break;
case 1099 : w=’ы’; break;
case 1101 : w=’э’; break;
case 1102 : w=’ю’; break;
case 1103 : w=’я’; break;
case 1025 : w=’Ё’; break;
case 1105 : w=’ё’; break;
case 1028 : w=’Є’; break;
case 1108 : w=’є’; break;
case 1031 : w=’Ї’; break;
case 1111 : w=’ї’; break;
case 1030 : w=’І’; break;
case 1110 : w=’і’; break;
case 8470 : w=’№’; break;
default : w=j;
void MY_chartoQString(QString *str,const char* qwe) <
unsigned short s[150];
int i;
Qt — Как конвертировать QString в char (НЕ char *)
Решение
Другие решения
Если вы утверждаете, что это возвращает символ *:
Тогда, очевидно, это получит первый символ, который будет char :
Это может выглядеть не очень красиво, и, возможно, есть лучшие способы получения первого символа, но по определению этот код должен (вероятно, должен) Работа.
Используйте оператор индекса, чтобы получить первый символ строки:
Тем не менее, нет необходимости конвертировать в std::string так что следующая идея лучше:
Основная проблема заключается в том, что QString находится в UTF-16 и содержит QChar s, двухбайтовые символы. Если ваш персонаж может быть представлен в кодировке latin-1, вы должны использовать
В противном случае вам понадобится больший тип (ПРИМЕЧАНИЕ: даже это сокращает символы, отличные от BMP, пополам):
Как уже говорили другие, используйте QString :: operator []. Использование этого в QString вернет QCharRef, вспомогательный класс, эквивалентный QChar. Поскольку QChar предназначен для поддержки символов Юникода, существует только одна дополнительная спецификация. Из QChar в документации qt (4.7):
QChar предоставляет конструкторы и операторы приведения, которые облегчают
конвертировать в и из традиционных 8-битных символов. Если вы определили
QT_NO_CAST_FROM_ASCII и QT_NO_CAST_TO_ASCII, как объяснено в
Документация QString, вам нужно будет явно вызвать fromAscii () или
fromLatin1 () или используйте QLatin1Char, чтобы создать QChar из 8-битного
char, и вам нужно будет вызвать toAscii () или toLatin1 (), чтобы получить
8-битное значение обратно.
Моя сборка Qt не позволит
char c = QString(«myTextHere»)[0];
и вместо этого я бы использовал
char c = QString(«myTextHere»)[0].toAscii();



