tags:

views:

269

answers:

4

hi! all, I was tryin to convert a QSting to char* type but by following methods,but those does'nt 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 elobrate the possible flaw with this method ,or tell alternative method.

+3  A: 

Well, the Qt FAQ says:

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

So perhaps you're having other problems. How exactly doesn't this work?

Eli Bendersky
+1  A: 

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".

gregseth
+1  A: 

Maybe

my_qstring.toStdString().c_str();

I's far from optimal, but will do the work.

davidnr
A: 

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:

// 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);
alex