0

can i please get some guidance to constructing a parser for an input file, I've been looking for a help for weeks, the assignment is already past due, I would just like to know how to do it.

The commented code is what I've tried, but i have a feeling it is more serious than that. I have a text file and I want to parse it to count the number of times that words appear in the document.

   Parser::Parser(string filename) {
   //ifstream.open(filename);

  // source (filename, fstream::in | fstream::out);

 }
6
  • 1
    The Dragon Book: en.wikipedia.org/wiki/… Commented Apr 20, 2011 at 19:53
  • You'll probably need to tell us about the format of the input file before we can give any really intelligent advice. Commented Apr 20, 2011 at 19:54
  • 1
    @Nikolai N Fetissov: I think a book about C++ would be more appropriate. Commented Apr 20, 2011 at 19:55
  • Are you having trouble parsing the string or reading the text file in? This will change the kinds of answers you receive. Commented Apr 20, 2011 at 19:56
  • all the words in the text file are in lower case, it is a a speech so many words, pauses and such Commented Apr 20, 2011 at 19:59

3 Answers 3

1

The commented code is what I've tried, but i have a feeling it is more serious than that.

I have a feeling you haven't tried a thing. So I am going to do the same.

Google is your friend.

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

Comments

0

To read a word:

std::ifstream  file("FileName");

std::string word;
file >> word; // reads one word from a file.


// Testing a word:
if (word == "Floccinaucinihilipilification")
{
     ++count;
}

// Count multiple words
std::map<std::string, int>   count;

// read a word
++count[word];

// To read many words from a file:

std::string word;
while(file >> word)
{
     // You have now read a word from a file
}

Note: That is a real word :-)
http://dictionary.reference.com/browse/floccinaucinihilipilification

4 Comments

so how do i make the parser read the whole file instead of just one word?
See stackoverflow.com/questions/625247/… for reading the whole file.
I just followed that link. The accepted answer is wrong. Update my answer.
@Benjamin Lindley: No. My friends and I have an on going bet (since university) to see who can use the word in everyday conversation (without forcing it).
0

Take a look at the answers in How do you read a word in from a file in C++? . The easiest way is to use an ifstream and operator>> to read single words. You can then use a standard container like vector (as mentioned in the link above) or map<string, int> to remember the actual count.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.