QTextStream 读取一个字符串直到制表符

QTextStream read a string until tab

我的文件名中有 space,但用制表符分隔。如何使用 QTextStream?

逐一阅读它们

正常的方式是按制表符和 spaces(实际上是任何 QChar::isSpace())分割,这不是我想要的:

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"

现在我使用 QString::split() 而不是 QTextStream 作为解决方法,但我宁愿使用 QTextStream.

无法使用 QTextStream 执行您想要的操作。

请阅读下文link:

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

读取文本文件时使用QTextStream一般有以下三种方式:

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().

建议:如果您正在生成文件,请不要在文件名之间使用空格。使用下划线。

如果您真的想以流的方式进行,另一种选择是创建自定义 TextStream 并覆盖 >> 运算符。

#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"
}

您可以阅读有关 QTextStream 流运算符的 Qt 文档:

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).

所以这个运算符从流中读取由空格分隔的单词。对于这种情况,没有办法更改分隔字符。所以你最好坚持使用 QString::split() 方法。或者将文件名更改为没有空格(如果可能)并用空格分隔文件名。