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