I was trying to convert a QString to char* type by the following methods, 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 elaborate the possible flaw with this method, or give an alternative method?
Well, the Qt FAQ says:
So perhaps you're having other problems. How exactly doesn't this work?
Maybe
my_qstring.toStdString().c_str();
or safer, as Federico points out:
It's far from optimal, but will do the work.
The easiest way to convert a QString to char* is qPrintable(const QString& str), which is a macro expanding to
str.toLocal8Bit().constData()
.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:
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".
EDITED
this way also works
the Correct Solution Would be like this
If your string contains non-ASCII characters - it's better to do it this way:
s.toUtf8().data()
(ors->toUtf8().data()
)