It would be best to understand how QDebug
works internally. That way you can easily modify it to suit your needs. Whenever you use the qDebug()
function, it returns a QDebug
object. By default QDebug
always outputs a space after any use of operator <<
.
The QDebug
class internally contains a QString
. Every time you use operator <<
you are appending to that internal QString. This QString is printed via qt_message_output(QtMsgType, char*)
when the QDebug
object is destroyed.
By default qt_message_output
always prints the string followed by a newline.
Normal Output
qDebug() << "Var" << 1;
This will output Var 1
. This is because qDebug
will create a QDebug
object which appends a space after each call to operator <<
. So that will be Var
+
+ 1 +
.
Without Spaces
You can use QDebug::nospace
to tell QDebug
not to append a space after each call to operator <<
.
qDebug().nospace() << "Var" << 1;
This will output Var1
as that QDebug
object is no longer printing spaces.
Without New Lines
Not adding the \n
at the end of the string is a little bit harder. Since QDebug
internally only passes the string to qt_message_output
when it is destroyed, you can delay the destruction of that QDebug object -
QDebug deb = qDebug();
deb << "One" << "Two";
deb << "Three";
This will print One Two Three
and then append a new line.
If you never want a new line to be printed, you will have to change the behaviour of qt_message_output
. This can be done by installing a custom handler.
void customHandler(QtMsgType type, const char* msg) {
fprintf(stderr, msg);
fflush(stderr);
}
// Somewhere in your program
qInstallMsgHandler(customHandler);
qDebug() << "One" << "Two";
qDebug().noSpace() << "Three" << "Four";
This will print One Two ThreeFour
.
Be warned that this will affect all of the qDebug statements in your program. If you want to remove the custom handler, you should call qInstallMsgHandler(0)
.
qDebug(const char* msg, ...)
As indicated by the other answers you can also use the qDebug
function to print strings in a format similar to that of printf
. This way you can avoid the extra spaces that are appended by QDebug
.
However, qDebug
internally still uses qt_message_output
, so you will still get a newline at the end unless you install your own handler.
var1.toStdString().c_str()
I'd recommendqPrintable( var1 )
. Both work fine, butqPrintable()
looks nicer. :) – Unni