Вопрос

I have a question regarding reading a *.txt file with C++. I'm trying to read only the part of data between some specific sign like [start] and [end].

How I can do that?

I know how to open and read the whole file but I don't know how to read only a part of it with such requirements.

Это было полезно?

Решение

Use std::string and std::getline to filter out lines and go from there. Example:

std::ifstream input("someText.txt");
std::string line;
unsigned int counter = 0;
while (std::getline(input, line))
{
    std::cout << "line " << counter << " reads: " << line << std::endl;
    counter++;
}

Furthermore you can use the substr() method of the std::string class to filter out sub strings. You can also tokenize words (instead of lines) with std::getline using the optional third argument, which is the tokenizer. Example:

std::ifstream input("someText.txt");
std::string word;
unsigned int counter = 0;
while (std::getline(input, word, ' '))
{
    std::cout << "word #" << counter << " is: " << word << std::endl;
    counter++;
}

Другие советы

The way to go here would be to read word by word until you get the wanted start tag, then you read and save all words until the end tag is read.

If you are creating that .txt file by yourself, create it in a structured way, keeping offsets and size of different blocks in the beginning. if so, you can read the offset of required block of data from the beginning and jump to there using fseek (or similar). Otherwise, you have to read word by word.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top