Invalid Operands to Binary Conversion for QTextStream

1.4k Views Asked by At

I need to know about the conversion for QTextStream to a bool variable. Have a look at my code :

QFile file(SOME FILENAME);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) qDebug() << "FILE COULD NOT BE OPENED";
QTextStream stream(&file);

bool dBm = false;
if (!stream.atEnd()) stream >> dbM;

As my above expression is throwing the error for which I need help.

1

There are 1 best solutions below

0
Scheff's Cat On

There is no >> operator for QTextStream and bool out of the box.

The doc. of QTextStream mentions a lot of input operators but none for bool:

QTextStream & operator>>(QChar &c)
QTextStream & operator>>(char &c)
QTextStream & operator>>(short &i)
QTextStream & operator>>(unsigned short &i)
QTextStream & operator>>(int &i)
QTextStream & operator>>(unsigned int &i)
QTextStream & operator>>(long &i)
QTextStream & operator>>(unsigned long &i)
QTextStream & operator>>(qlonglong &i)
QTextStream & operator>>(qulonglong &i)
QTextStream & operator>>(float &f)
QTextStream & operator>>(double &f)
QTextStream & operator>>(QString &str)
QTextStream & operator>>(QByteArray &array)
QTextStream & operator>>(char *c)

However, it's not that complicated to add one for the personal joy.

The most complicated about this is what @Frank Osterfeld already mentioned in this comment – to define an adequate textual representation of true and false.

For my MCVE, I used simply 0 and 1.

testQTextStreamInputBool.cc:

#include <QDebug>
#include <QTextStream>

// a stream input operator for bool
QTextStream& operator>>(QTextStream &in, bool &var)
{
  char value;
  in >> value;
  var = value == '1';
  return in;
}

int main()
{
  QTextStream in(stdin);
  while (!in.atEnd()) {
    bool value; in >> value;
    qDebug() << "Read:" << (value ? "true" : "false");
  }
}

testQTextStreamInputBool.pro:

SOURCES = testQTextStreamInputBool.cc

QT = core

Compiled and tested in bash of cygwin64:

$ qmake-qt5 testQTextStreamInputBool.pro

$ make
g++ -c -fno-keep-inline-dllexport -D_GNU_SOURCE -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_CORE_LIB -I. -isystem /usr/include/qt5 -isystem /usr/include/qt5/QtCore -I. -I/usr/lib/qt5/mkspecs/cygwin-g++ -o testQTextStreamInputBool.o testQTextStreamInputBool.cc
g++  -o testQTextStreamInputBool.exe testQTextStreamInputBool.o   -lQt5Core -lpthread 

$ echo "0110010" | ./testQTextStreamInputBool
Read: false
Read: true
Read: true
Read: false
Read: false
Read: true
Read: false

$

Of course, it would make sense to overload the operator<<(QTextStream&, bool) as well to have a matching custom output for the custom input.

If not, the compiler will convert the bool to int, implicitly, and use QTextStream::operator<<(int). Hence, false will be written as 0, true as 1.

That's just what my overloaded bool stream input operator expects...