3

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.

Nejat
  • 31,784
  • 12
  • 106
  • 138
sashoalm
  • 75,001
  • 122
  • 434
  • 781

3 Answers3

3

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"
}
shinichy
  • 81
  • 1
  • 2
1

It is not possible to do what you want using QTextStream.

Please read below link:

http://qt-project.org/doc/qt-4.8/qtextstream.html

There are three general ways to use QTextStream when reading text files:

Chunk by chunk, by calling readLine() or readAll().
Word by word. QTextStream supports streaming into QStrings, QByteArrays and char* buffers. Words are delimited by space, and leading white space is automatically skipped.
Character by character, by streaming into QChar or char types. This method is often used for convenient input handling when parsing files, independent of character encoding and end-of-line semantics. To skip white space, call skipWhiteSpace().

Suggestion: If you are generating the files, please don't use spaces in between filenames. Use underscore.

CreativeMind
  • 897
  • 6
  • 19
0

You can read from the Qt documentation about QTextStream stream operator:

QTextStream & QTextStream::​operator>>(QString & str)

Reads a word from the stream and stores it in str, then returns a reference to the stream. Words are separated by whitespace (i.e., all characters for which QChar::isSpace() returns true).

So this operator reads the words from stream which are separated by white spaces. There is not a way to change the separation character for this case. So you are better to stick with the QString::split() method. or change the file names to not have spaces (if possible) and separate file names by white spaces.

Nejat
  • 31,784
  • 12
  • 106
  • 138