0

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?

Axel247
  • 23
  • 1
  • 3
  • If regex is an option, this might help: http://criticalindirection.com/2016/01/05/lex-based-config-parserreader/ – user31986 Jan 05 '16 at 11:45

2 Answers2

3

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • @user814628: You were prepared to use `std::getline`, so... small difference. – Kerrek SB Oct 03 '13 at 21:22
  • 1
    @user814628 No sense in rewriting code when code to do the same task is already written and well-tested. – Zac Howland Oct 03 '13 at 21:23
  • It's very easy to overlook some of the nifty features in the standard library ... ;) – goji Oct 03 '13 at 21:44
  • @KerrekSB judging from OP's code, it doesn't seem like he is at level where he would understand what exactly are those lines of code doing. I just posted a simple solution to which I believe he could grasp at this point more easily.However, I did fail to mention better solutions, to which you have provided. Thanks. – dchhetri Oct 03 '13 at 21:49
2

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

dchhetri
  • 6,926
  • 4
  • 43
  • 56