在C++中创建文件解析器

Creating a File Parser in C++

本文关键字:文件 创建 C++      更新时间:2023-10-16

我正在尝试创建一个解析器类,该类将解析基于" "的文件并将单词放入链表中。

class FileReader
{
public:
   FileReader(char* file)   
   {
    ifstream fout (file, ifstream::in);
    string hold;
    while (fout.good())
    {
        getline (fout, hold, " ");
        cout << hold;
    }
    fout.close();
    }
};

函数getline(fout, hold, " ")不识别 " " 作为分隔符。

我还没有对链表部分进行编码,所以这只是程序的解析部分。

还有没有更好的方法来创建解析器?

它应该像这样工作:

#include <fstream>
#include <iterator>
#include <list>
#include <string>
std::ifstream infile(file);
std::list<std::string> words(std::istream_iterator<std::string>(infile),
                             std::istream_iterator<std::string>());

现在words是空格分隔标记的链接列表。

教训:最好的代码是你不必编写的代码。

> getline 中的最后一个参数是char而不是string。查看您当前的代码,您想要getline(fout,hold,' ')或只是getline(fout,hold) - *如果您想要整行。

*: 编辑