0

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?

Quasy
  • 29
  • 5
  • I want to split the parsing process to functions. So when I expect for specific symbols, say digits, I to stop when I encounter a non-digit. And to get that non-digit, I'll have to first read it from the stream, meaning that in parsing next token (another function call), the character won't be available to me (answer to the previous comment) – Quasy Mar 10 '23 at 08:41
  • Someone answered below. To my surprise, it seems what you are asking is possible. Interesting problem though; as of right now, I would probably make it so the text stream contains some sort of separator (e.g. xml) or if chunks of text should be parsed by regexp (with your example, split the string into `(\d+)(.+)` to have digits first and the rest afterward), with each match being sent to the appropriate function. Or maybe use a `QBuffer` to store the text without ever going back in the text stream. I will try to spend some time trying to think if your approach truly is the best one. – Atmo Mar 10 '23 at 08:47

1 Answers1

2

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.

Pamputt
  • 173
  • 1
  • 11