从文件读入.多个分隔符?C++

Reading In From A File. Multiple Delimiters? C++

本文关键字:C++ 分隔符 从文件读      更新时间:2023-10-16

所以我试图从文件中读取一些信息,但我很难做到这一点。这是我尝试读入的文件的格式。

Name#Description
Name2#Description2 ...
NameX#DescriptionX
%
info1,info2,info3,info4 ...
infoX1,infoX2,infoX3,infoX4,
%
Keyword#Message

所以我要做的是在每次#后分解代码的第一部分,并将 Name 拆分为一个变量,将描述拆分为另一个变量。然后在第一个%之后,将每条信息拆分为它自己的变量。最后,在第二个%之后,将它们按#拆分,就像上面一样,但变量不同。

所以我尝试while(getline(inFile, str, '%')但它在第一行后停止阅读,然后转到%下的任何内容。在这里遇到一些麻烦,所以任何帮助将不胜感激!

下面是一个(不完整的)结构,用于执行此操作:

#include <fstream>
#include <iostream>
#include <string>
int main(void) {
    const char* in_file_path = "foo.txt";
    std::ifstream in_file(in_file_path);
    std::string buffer = "";
    while (std::getline(in_file, buffer)) {
        //parse input using `#` as separator...
        if (buffer.at(0) == '%') {
            // get position of `%` char in stream using (e.g.) in_file.seekg
            break;
        }
    }
    // after getting position of first `%` char in stream, this loop 
    // will start from this position in the file
    while (std::getline(in_file, buffer)) {
        // parse input using `,` as separator...
        if (buffer.at(0) == `%`) {
            // get position of `%` char in stream using (e.g.) in_file.seekg
            break;
        }
    }
    // ... and so on for as many separations as you need until you hit end of file
}

这依赖于使用(例如)seekg std::ifstream方法:

http://en.cppreference.com/w/cpp/io/basic_istream/seekg