[Solved] Convert content of QlineEdite to Char *
-
I apologize! and I agree SGaIst.
-
Thanks to all.
Any idea to convert const char * to char *?
Is this a abnormal conversion? -
[quote author="MohammadReza" date="1396059354"]
Is this a abnormal conversion?[/quote]
Usually yes, it is not good idea to do a const cast on a pointer to a buffer that you received.
If you need to modify such buffer then make a copy, modify and put it back using api.
But if you want it then use standard c++ const_cast.
@
const char* bar;
char* foo = const_cast<char*>(bar)
@ -
Thanks to dear andreyc & other friends reply my question.
Solved!Ya Ali.
-
just use
@
byteArray.data();
@
instead of
@
byteArray.constData();
@
if you need a non const pointer (no need for a cast), but the question is why do you need that at all? I would not suggest you modify the data in the QByteArray via the char* array.. -
Hi dear Xandeer84.
I searched & found another way. Like this:@
QString MyQString = "Only Allah";
const char *MyConstChar = MyQString.toStdString().c_str();
@ -
You might lose information if you do that, because a std::string cannot contain all the unicode chars from the QString I think.
I think it would help if you tell us what you want to do with that char* and why you need it. -
I had a function that received char *.
There isn`t anymore, because i changed it const char *. -
[quote author="andreyc" date="1396066897"]@
const char* bar;
char* foo = const_cast<char*>(bar)
@
[/quote]That sounds like a really bad idea in this case. Nobody expects the const char* to change, so any changes made will cause trouble.
-
@SGaist Hi, I had an issue with data corruption because of this. In this example I can see that you create a local variable QByteArray instead. Could you please clarify why the content of the QByteArray in one single line case is temporary? I may assume it is because it is called implicitly. In my example I used toStdString().c_str(), in the current function of my example it printed out with qDebug OK but when reading that global const char* in another place it was garbage.
-
@Jc_Opc Hi,
It's a question of object lifetime.
In this case:
const char * characters = ui->lineEdit->text().toLatin1().data();
the QByteArray returned by toLatin1 ends its life on the same line it was created.
Thereforecharacters
is pointing invalid memory as soon as the line ends.You have the exact same issue:
toStdString().c_str();
The std::string returned by toStdString() ends its life the same way as the QByteArray above.
qDebug() << myQString.toStdString().c_str();
works because everything happens on the same line.