6

I am trying to use some vector data's name with struct. I am trying to get see which name in qDebug()

To be more clear:

const std::string& testName = "asdfqwer";
qDebug() << testName;

It gives en error message in build:

Error: no match for 'operator<<' in 'qDebug()() << testName'

I don't have options to change const std::string& type. Could you please help me to solve this issue without changing type?

Jablonski
  • 18,083
  • 2
  • 46
  • 47
goGud
  • 4,163
  • 11
  • 39
  • 63

2 Answers2

17

qDebug() does not know anything about std::string but it works with const char*. Appropriate operator you can find here. You can achieve this with data() or with c_str() which is better as Jiří Pospíšil said.

For example:

const std::string& testName = "asdfqwer";
qDebug() << testName.data() << testName.c_str();

Aslo you can convert std::string to QString with QString::fromStdString.

Jablonski
  • 18,083
  • 2
  • 46
  • 47
  • 1
    same you can use convertion to the QString with the QString::fromStdString – johngull Dec 08 '14 at 13:18
  • Amazing.. I didn't know that behaviours of qDebug() – goGud Dec 08 '14 at 13:20
  • 7
    It'd be better to use `c_str()` instead of `data()` as the latter is not required to be null-terminated (until C++11). – Jiří Pospíšil Dec 08 '14 at 13:21
  • @johngull Yes, you are right, but I thought that OP use here C++ only types, but I added this to answer, it correct and OP can choose what he wants. – Jablonski Dec 08 '14 at 13:25
  • @JiříPospíšil I added c_str() to my answer. Thank you. – Jablonski Dec 08 '14 at 13:25
  • @Chernobyl I think it is natural to use Qt types if you use qDebug. Impossible to use qDebug without using QtCore, so QString is available for him. Anyway, the main point here that convertion needed. – johngull Dec 08 '14 at 13:29
8

If you need writing std::string to qDebug() often in your code, you can implement this function globally (for example in you main.cpp):

#include <QDebug>
#include <string>

QDebug& operator<<(QDebug& out, const std::string& str)
{
    out << QString::fromStdString(str);
    return out;
}

int main()
{
    std::string jau = "jau";
    qDebug() << jau;
    return 0;
}
mrts
  • 16,697
  • 8
  • 89
  • 72
Simon Warta
  • 10,850
  • 5
  • 40
  • 78