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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@user814628: You were prepared to use std::getline, so... small difference.
@user814628 No sense in rewriting code when code to do the same task is already written and well-tested.
It's very easy to overlook some of the nifty features in the standard library ... ;)
@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.
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

1 Comment

getline(fout, hold) will get an entire line ... not just individual words.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.