0

this is my current read file code:

void Dictionary::processFile() {
    ifstream fin;
    fin.open("article.txt");
    if (fin.fail( )) {
        cout << "Input file opening failed.\n";
        exit(1);
    }

    string word;

    while (!fin.eof()) {
        fin >> word;
        cout << word << endl;
    }
    cout << endl;
    fin.close();
}

How can I make my code ignore symbols(".';:! etc.) and only output/read words? at the moment it is reading every single symbol on the article. example "test.", "them,"

nanjero05
  • 101
  • 1
  • 1
  • 10
  • 4
    What kind of symbol d you mean? Can you provide a minimal example for `article.txt`? – smkanadl May 10 '16 at 08:58
  • 7
    Don't use `!fin.eof()` in the while condition, instead put `fin >>word` directly as the conditon. See [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/q/5605125/1942027) for more info. – user1942027 May 10 '16 at 08:58
  • @smkanadl basically all symbols like . , ; ' " / ! @ etc. – nanjero05 May 10 '16 at 09:10
  • @RaphaelMiedl when I tried using fin>>word it skipped the first and last word in my txt file. why? – nanjero05 May 10 '16 at 09:14
  • 2
    You included ' in the undesired symbols. What's the expected behavior with words like "what's", "don't" or "I'll"? – Bob__ May 10 '16 at 09:26

2 Answers2

2

If you can use Boost.Iostrems, you may to write own InputFilter for your stream. See the details here http://www.boost.org/doc/libs/1_60_0/libs/iostreams/doc/tutorial/writing_filters.html

AnatolyS
  • 4,111
  • 14
  • 27
2

Read "words" much like you do now, but then filter out the unwanted characters from the string before printing the "word".

C++ have many algorithmic functions that can help you with this. For your purpose you could look at e.g. std::remove_if and do something like

static std::string const symbols = "\".';:!";

while (fin >> word)
{
    word.erase(std::remove_if(word.begin(), word.end() [symbols&](char const& ch) {
        return std::any_of(symbols.begin(), symbols.end(), [ch](char const& sym) {
            return ch == sym;
        });
    });

    if (!word.empty())
    {
        // Do something with the "word"
    }
}
Some programmer dude
  • 363,249
  • 31
  • 351
  • 550