Convert QString to char *

I tried to convert QString to char * type in the following ways, but they don't seem to work.

//QLineEdit *line=new QLineEdit();{just to describe what is line here} QString temp=line->text(); char *str=(char *)malloc(10); QByteArray ba=temp.toLatin1(); strcpy(str,ba.data()); 

Can you explain the possible disadvantage of this method or give an alternative method?

+71
c ++ qt qstring qtcore
Mar 26 '10 at 13:59
source share
8 answers

Well, the Qt FAQ says:

 int main(int argc, char **argv) { QApplication app(argc, argv); QString str1 = "Test"; QByteArray ba = str1.toLocal8Bit(); const char *c_str2 = ba.data(); printf("str2: %s", c_str2); return app.exec(); } 

So maybe you have other problems. How exactly does this not work?

+99
Mar 26
source share
— -

maybe

my_qstring.toStdString().c_str();

or safer, as Federico points out:

 std::string str = my_qstring.toStdString(); const char* p = str.c_str(); 

This is far from optimal, but it will work.

+38
Jun 01 '10 at
source share

The easiest way to convert QString to char * is qPrintable (const QString & str) , which is a macro expanding to str.toLocal8Bit().constData() .

+33
May 10 '16 at 8:51
source share

David's answer works fine if you only use it to output to a file or display on the screen, but if a function or library requires char * for parsing, then this method works best:

 // copy QString to char* QString filename = "C:\dev\file.xml"; char* cstr; string fname = filename.toStdString(); cstr = new char [fname.size()+1]; strcpy( cstr, fname.c_str() ); // function that requires a char* parameter parseXML(cstr); 
+6
Aug 04 '10 at 17:56
source share

Your string may contain non-Latin1 characters, which results in undefined data. It depends on what you mean by "it doesn't seem to work."

+2
Mar 26 '10 at 2:37
source share

The correct solution would be like this:

  QString k; k = "CRAZYYYQT"; char ab[16]; sprintf(ab,"%s",(const char *)((QByteArray)(k.toLatin1()).data()) ); sprintf(ab,"%s",(const char *)((QByteArray)(k.toStdString()).data())); sprintf(ab,"%s",(const char *)k.toStdString().c_str() ); qDebug()<<"--->"<<ab<<"<---"; 
+2
29 '16 at 8:22
source share

EDITING

this method also works

 QString str ("Something"); char* ch = str.toStdString().C_str(); 
+2
May 31 '18 at 15:32
source share

If your string contains non-ASCII characters, it is best to do this as follows: s.toUtf8().data() (or s->toUtf8().data() )

0
Dec 11 '18 at 16:17
source share



All Articles