QString to char* conversion
Well, the Qt FAQ says:
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QString str1 = "Test";
QByteArray ba = str1.toLocal8Bit();
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?
Can't convert QString to Const Char*
Try dir.rename(dir.dirName(), name);
You are trying to invoke a member function without an instance.
Since rename()
is a member function of QDir
, you need a QDir
instance in order to invoke it. So rather than just calling rename()
which invokes who knows what, you need to dir.rename()
.
QDir::rename()
actually takes 2 QString
s as parameters, but that other function you are invoking takes two raw strings, so you don't really need to convert the strings, you were just calling the wrong function.
bool QDir::rename(const QString & oldName, const QString & newName)
You are most likely calling rename()
from <stdio.h>
, which could also work given that the parameters are correct and the OS can rename the directory, in that case you will need to convert to "raw" C-style strings via yourString.toLatin1().constData()
. But since you are using Qt, you might as well use the QDir
API, which works directly with QString
.
If it still doesn't work, then either your input parameters are wrong, or there is something preventing the OS from rename the directory, for example a file currently in use.
Qt - How to convert QString to char (NOT char*)
I'm pretty sure I found a way to convert the value without getting the error about QCharRef, I found if I use the QString::at()
function to get the first index instead of QString("myText")[0]
, and then use toAscii()
on that value, it seems to work and produce the correct value I want. In other words, this is what I did:
char c = QString("A").at(0).toAscii();
Clean way to convert QString to char * (not const char* !!!!)
This is simple:
QByteArray array = string.toLocal8Bit();
char* buffer = array.data();
You can also use toLatin1
or toUtf8
instead of toLocal8Bit
. Note that neither of them can be queued with data
call. And toStdString().c_str()
is also invalid. This is because any QByteArray
or std::string
produced in such a way is temporary and will be destroyed immediately destroying char buffer with it. You need to store QByteArray
in a local variable while you're using the buffer.
Also note that Qt provides QByteArray
class to deal with char arrays. Generally there is no need to use char*
, you can do almost anything with QByteArray
.
How do i convert a QString to a char*
This is because data() returns the address of the buffer in the bytearray, you can read it, but obviously you should not write it.
You have your own buffer outside the bytearray. If you want the data, you should copy the buffer of bytearray into the myMailBoName.
use memcpy function
Converting QString to char*
See here at How can I convert a QString to char* and vice versa?
In order to convert a QString to a
char*, then you first need to get a
latin1 representation of the string by
calling toLatin1() on it which will
return a QByteArray. Then call data()
on the QByteArray to get a pointer to
the data stored in the byte array. See
the documentation:https://doc.qt.io/qt-5/qstring.html#toLatin1
https://doc.qt.io/qt-5/qbytearray.html#dataSee the following example for a
demonstration: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();
}
Note that it is necessary to store the
bytearray before you call data() on
it, a call like the followingconst char *c_str2 = str2.toLatin1().data();
will make the application crash as the
QByteArray has not been stored and
hence no longer existsTo convert a char* to a QString you
can use the QString constructor that
takes a QLatin1String, e.g:QString string = QString(QLatin1String(c_str2)) ;
See the documentation:
https://doc.qt.io/qt-5/qlatin1string.html
Of course, I discovered there is another way from this previous SO answer:
QString qs;
// Either this if you use UTF-8 anywhere
std::string utf8_text = qs.toUtf8().constData();
// or this if you on Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();
Different results for QString to const char*
What you are observing is undefined behavior.
The call to toLatin1()
creates a temporary QByteArray
, which is destroyed immediately after that line, since you do not store it. The pointer obtained by data()
is left dangling and might or might not print something useful.
Correct version:
const QByteArray& latinName = name.toLatin1();
const char* strName = latinName.data();
how to convert QString to char**
doStuff
is expecting an array of strings not a single string.
Something like this should work:
std::vector<std::string> command;
command.push_back(QString("-w=%1").arg("6").toUtf8().toStdString());
command.push_back(QString("-h=%2").arg("16").toUtf8().toStdString());
command.push_back(QString("-s=%3").arg("0.25").toUtf8().toStdString());
command.push_back("-o=test.yml");
command.push_back("-op");
command.push_back("-oe");
std::vector<char*> cstr;
std::transform(command.begin(), command.end(), std::back_inserter(cstr),[](std::string& s){return s.data();});
doStuff(cstr.size(), cstr.data());
Convert a QString to a const char*
Your problem is that you are returning an invalid pointer:
const auto ba = m_Message.toLocal8Bit(); // here you create a bytearray
return ba.constData();//here you take the pointer to the data of the bytearray
//then you destroy the array, hence the pointer.
//then you return an invalid pointer
You have different behaviors in the different platforms because it is not warrantied when the pointer will not be longer available. It depends on the platform, the compiler, the compilation flags, etc.
Related Topics
What Is the Easiest Way to Print a Variadic Parameter Pack Using Std::Ostream
Winapi Sleep() Function Call Sleeps for Longer Than Expected
How to Initialize C++ Object Member Variables in the Constructor
How to Use Std::Async Without Waiting for the Future Limitation
C++ Header Files, Code Separation
Multiple Definition of Template Specialization When Using Different Objects
Boost::Asio:Io_Service.Run() VS Poll() or How to Integrate Boost::Asio in Mainloop
Are C++17 Parallel Algorithms Implemented Already
What Does the Standard Say About How Calling Clear on a Vector Changes the Capacity
Variadic Function Template with Pack Expansion Not in Last Parameter
How to Specify Preference of Library Path
What Does '&' Do in a C++ Declaration
C/C++ Header and Implementation Files: How Do They Work
How to Read-Write Into/From Text File with Comma Separated Values