printf for qstring
-
See qPrintable() - but why?
-
On Windows you can also use
printf("%ls\n", qUtf16Printable(tmp))
which has the nice benefit of (usually) avoiding conversion. Note it's not applicable to any platform wherewchar_t
is not 2 bytes. -
generally not the best way to handle qstrings but in direct answer to your question:
QString mystring("some string"); printf("%s\n", mystring.toStdString().c_str());
There may be a Qstring direct method to get the const char* address of the stirng data but the method I show is pretty solid.
IMHO, you really shouldn't be using c style printf in C++ code. Learn to use the streams I/O.
-
This post is deleted!
-
@Kent-Dorfman said:
generally not the best way to handle qstrings
Agreed, especially that it requires two libraries to do a simple task. You can stay in Qt world with
printf("%s\n", mystring.toUtf8().data());
but that's essentially what
qPrintable()
does so what @Christian-Ehrlicher said. -
@Christian-Ehrlicher said in printf for qstring:
See qPrintable() - but why?
oh, QT was compiled as lib on my machine so I wasn't able to use qDebug or any qWarning etc.
also I have a custom function that printout the file name, and line numbers using printf for debugging. unless there is some c++ or Qt way to print out the file name and line numbers,?
-
@s002wjh said in printf for qstring:
so I wasn't able to use qDebug or any qWarning etc.
See qInstallMessageHandler() and/or QLoggingCategory or use a proper logging library (printf is no function to print out debug / logging stuff) like e.g. Log4Qt
-
Note it's not applicable to any platform where wchar_t is not 2 bytes.
I'm not sure this limitation exists.
qUtf16Printable
is used in Qt itself on Linux and Windows at least. Which platforms did you have in mind?Regards
-
@aha_1980 said in printf for qstring:
I'm not sure this limitation exists.
Isn't the size of
wchar_t
on most Linux distros and mac 4 bytes?%ls
takeswchar_t*
and as far as I can tell allqUtf16Printable
does is some forceful casting to silence compiler warnings. Still, it uses the underlyingQString
data directly.QString
uses 2 byte chars, so I don't see how this would work?
Unless there's more funky trickery going on on Linux, I don't know. I mostly keep to Windows so if you know how that works I'd be interested to learn. -
you are right: https://doc.qt.io/qt-5/qtglobal.html#qUtf16Printable states that the result is no valid
wchar_t
. so you can use the result withqDebug
andQString::asprintf
, but not withprintf
.Regards