Search code examples
c++qtqtextstream

QTextStream read a string until tab


I have filenames that have space in them, but are separated by tabs. How can I read them one by one using a QTextStream?

The normal way would split by tabs AND spaces (actually any QChar::isSpace()), which is not what I want here:

QString s = "file 1.txt\tfile 2.txt";
QTextStream st(&s);
st >> s1 >> s2; // <--- This won't work, it'll give me "file" and "1.txt"

Right now I'm using QString::split() instead of QTextStream as a workaround, but I'd rather use a QTextStream.


Solution

  • If you really want to do it in a stream manner, another option is to create a custom TextStream and override >> operator.

    #include <QString>
    #include <QStringBuilder>
    #include <QTextStream>
    
    class MyTextStream : public QTextStream {
    public:
      MyTextStream(QString* str) : QTextStream(str) {}
    
      MyTextStream& operator>>(QString & str) {
        QChar ch;
        while (!atEnd()) {
          QTextStream::operator >>(ch);
          if (ch == '\t') {
            break;
          }
          str = str % ch;
        }
        return *this;
      }
    };
    
    int main() {
      QString s1, s2;
      QString s = "file 1.txt\tfile 2.txt";
      MyTextStream st(&s);
      st >> s1 >> s2; // <--- s1 becomes "file 1.txt" and s2 becomes "file 2.txt"
    }