Qt5 convert QString into char [] or char *
-
Hello, I googled a lot over that theme, all deprecated or do not work
QString hello = "Hello World"; ---> to char *cHello or to char cHello[30]
How to convert in Qt5 to a standard c++ char array?
i tried for(int i = 0; ;i++) cHello[i] = hello.at(i); .... and much more, but without sucess
Someone kind enough to help? please help :-)
thanks in advance. greetings
-
Hello, I googled a lot over that theme, all deprecated or do not work
QString hello = "Hello World"; ---> to char *cHello or to char cHello[30]
How to convert in Qt5 to a standard c++ char array?
i tried for(int i = 0; ;i++) cHello[i] = hello.at(i); .... and much more, but without sucess
Someone kind enough to help? please help :-)
thanks in advance. greetings
-
Just a typo. It's
std::string QString::toStdString() const. -
hi yczo,
tryhello.toStdString().c_str();
mind the small letter -
you are right, the pointer you get is const, but you can do something like
char cHola[512] = {0}; std::copy(hello.toStdString().begin(),hello.toStdString().end(),cHola);but remind that there´s no boundary check on cHola and you get nonsens if it´s not a basic_string<char>
-
but... there is not a way to direct obtain a char array instead of a string? the question was over an char array hehee ;-)
char *cHola =
Thank you very much (I appreciate the kindness)...
-
Hello and thank you; I need "char *hola" or "char hola[maxSize]" for send simply chars to serial port through Windows handler
Greetings
@yczo said:
I need "char *hola" or "char hola[maxSize]" for send simply chars to serial port through Windows handler
You're better of using
QSerialPort(which acceptsQByteArray) and respecting the string's encoding. Also referencing temporaries can be inconspicuously dangerous in some cases. Consider this (modified from @sneubert's example):char * string = hello.toStdString().c_str(); // Now we get a dangling pointer to a location we don't own! WriteFile(yourComHandle, string, hello.length(), &dw_bytesWritten, NULL); // Might work, depending on the compiler, might get a segfaultHow about this, doesn't it look better:
QSerialPort port; // ... init and so on ... QByteArray data = hello.toLatin1(); // Enforce latin1 encoding (or utf8, or local 8-bit or whatever your device is expecting) port.write(data); port.waitForBytesWritten(1000); // Only for illustration, you can (and should) use the async API // ... and so on ...Or, if you really insist on using
char *, then enforce the encoding to a byte-array and then get the char pointer from there:QByteArray string = hello.toLatin1(); char * strdata = string.data(); // This pointer is valid during the lifetime of the QByteArray instance (provided the byte array is not changed in the meantime)