简体   繁体   中英

Creating a File Parser in C++

I am trying to create a parser class that will parse a file based on " " and place the words into a linked list.

class FileReader
{
public:
   FileReader(char* file)   
   {

    ifstream fout (file, ifstream::in);

    string hold;

    while (fout.good())
    {
        getline (fout, hold, " ");
        cout << hold;

    }

    fout.close();

    }

};

The function getline(fout, hold, " ") is not recognizing " " as the delimiter.

I have not coded the linked list part as of yet so this is just the parsing part of the program.

Also would there be a better way to create a parser?

It should just work like this:

#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>());

Now words is your linked list of whitespace-separated tokens.

Lesson: The best kind of code is the one you don't have to write.

The last parameter in getline is a char not a string . Looking at your current code, you want getline(fout,hold,' ') or just getline(fout,hold) -- *if you want the whole line.

* : edit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM