Return one line to a C ++ text file

my program reads a line from a text file using:

std::ifstream myReadFile("route.txt"); getline(myReadFile, line) 

And if it finds what I'm looking for (tag), it will save that string in temp String. I will not continue this until I find some other tag, if I find another tag, I want to go back to the previous line so that the program reads, if again, like some other tags and do something else .

I look at putback () and unget (), I am confused about how to use them, and if they might be the right answer.

+5
source share
2 answers

It would be best to consider a one-pass algorithm that stores in memory what might be needed in the first tag without going back.

If this is not possible, you can "mark" the position of the stream and later execute it using tellg() and seekg() :

 streampos oldpos = myReadFile.tellg(); // stores the position .... myReadFile.seekg (oldpos); // get back to the position 

If you are reading recursively embedded tags (e.g. html), you can even use stack<streampos> to click and place positions while reading, However, keep in mind that performance is slowed by such reverse / reverse accesses.

You mentioned putback() and unget() , but they are limited to one char and don't seem to be suitable for your getline() approach.

+6
source

The simplest thing, if you ever want to roll back one line, always have to keep track of the line you're in and the line before.

It supports the variable cur , which stores the current line, and prev , which stores the previous one. When you move to the next line, copy cur to prev and read the new line in cur .

This way you always have the previous line available.

+1
source

Source: https://habr.com/ru/post/1208490/


All Articles