[SOLVED] Convert Qstring to char* and back
-
why is it so hard to do so ?
!http://i57.tinypic.com/2yynk9i.png(example)!i tried also :
1 - str.toStdString().c_str(); but returns const char .
2 - str.toLocal8Bit().data(); (same trash as utf8 see below )in the image you see ip which qstring (1.1.1.1), in function ipValid() i convert it to char* str .
you can see in the value of str to the right of the image (debugging mode) ,which is trash . -
Not sure what sure what you are trying to achieve. Here is simple one based on your question.
QString data("1.1.1.1"); qDebug() << data; char *datachar = data.toLocal8Bit().data(); qDebug() << datachar; qDebug() << QString(datachar);
If you want break the string based on "." you can use QString.split as well.
-
Hi,
To add to Dheerendra, if you really want to validate an IP address, you should rather use a regular expression.
If it comes from a user through a QLineEdit, you can also use a validator to ensure the user is only entering correct data.
-
thanks for tips on validating ip , but this isn't the only place i need to convert qstring to char* .
[quote author="Dheerendra" date="1408982078"]Not sure what sure what you are trying to achieve. Here is simple one based on your question.
char *datachar = data.toLocal8Bit().data();
[/quote]
i tried this method , but it doen't convert right , when i do :
char* str = ip.toLocal8Bit().data(); (ip=1.1.1.1)
str isn't 1.1.1.1 , see picture value of str . -
Are you taking about Quotes ? which are sorounding the string ? These quotes are not part of string.
Here is the output of my program.
"1.1.1.1"
1.1.1.1
"1.1.1.1" -
this is the output on my machine :
!http://i58.tinypic.com/j7f7d3.png(output)!is there something wrong with my qt ? i dont understand im new to qt so sorry if its a silly mistake
-
which platform ?
-
windows 8.1 32bit
Qt Creator 3.1.2 Based on Qt 5.3.1 (MSVC 2010, 32 bit)
-
QString::toLocal8Bit::data construct a temporary QByteArray object which will be destroyed and hence you got "bullshit" datachar contents.
QByteArray ba = data.toLocal8Bit();
char* datachar = ba.data();
In this way ba object will be destroyed on function exit -
[quote author="cincirin" date="1408986595"]QString::toLocal8Bit::data construct a temporary QByteArray object which will be destroyed and hence you got "bullshit" datachar contents.
QByteArray ba = data.toLocal8Bit();
char* datachar = ba.data();
In this way ba object will be destroyed on function exit[/quote]thank you very much sir , you r right
-
@
void barStd()
{
QString ip = "1.1.1.1";
qDebug() << "ip =" << ip;
char* localdata = ip.toLocal8Bit().data();
std::cout << "std::cout char* localdata = " << localdata << std::endl;
}void barqDebug()
{
QString ip = "1.1.1.1";
qDebug() << "ip =" << ip;
char* localdata = ip.toLocal8Bit().data();
qDebug() << "qDebug() char* localdata = " << localdata;
}
@and output
@
ip = "1.1.1.1"
qDebug() char* localdata =
ip = "1.1.1.1"
std::cout char* localdata = 1.1.1.1
@