C++ Qt5 : How to unread a character to QTextStream?

76 views Asked by At

I'm parsing tokens with QTextStream to extract characters one by one calling stream >> ch.

I wonder if there is a way to get a character back to stream, so it will be the next character read from it.

stream << ch always adds one character to the end of the stream, but is there a way to "unget" QChar to the top?

1

There are 1 answers

0
Pamputt On

You have to use QTextStream::seek(qint64 pos) to achieve this. Of course, you need to store the previous position in a variable. Here is something in pseudocode (not tested).

QTextStream stream(aString);
QChar ch;
qint64 previous_pos=0;
while(! stream.atEnd()) {
   stream >> ch;
   if(condition) {// put here the condition you are interested in
      stream.seek(previous_pos);
      continue;
   }
   previous_pos++;
}

Note that you may also use QTextStream::pos() (instead of previous_pos) but the documentation say this operation can be expensive.