0

I am stuck on a small part of a task I am trying to complete and each word must be trimmed so that a word contains only alphabetic letters when I read from a .txt file. This is apart of an AVL tree yes but the problem I believe lies within the reading of the text document.

I have tried ise isalpha but can not get it to work and have run out of ideas and am stuck in a situation here. I will appreciate any help given to me!

           cout << "Input a file name (dictionary.txt):" << endl;
            cin >> file;
            myfile.open(file);
            if (!myfile) {
                cout << "\nFile does not exist." << endl;
                return 0;
            }
            else cout << "\nDictionary has been loaded." << endl;
            while(!myfile.eof()) {
                myfile >> insert;
                DATA newItem;
                newItem.key = insert;
                tree.AVL_Insert(newItem);
                count++;
            }
Tom Tommy
  • 13
  • 3
  • 1
    1) "_I have tried ise isalpha but can not get it to work_" What's the problem with `std::isalpha`? 2) Relevant read: [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Algirdas Preidžius May 29 '19 at 14:41

1 Answers1

0

The algorithm library makes this easy:

#include <iostream>
#include <string>
#include <algorithm>

int main ()
{
    std::string s = "A1B2C3";
    s.erase (std::remove_if (s.begin (), s.end (), [] (auto c) { return !std::isalpha ((unsigned char) c); }), s.end ());
    std::cout << s;
}

Output:

ABC

Live demo

See also erase remove idiom

Paul Sanders
  • 15,937
  • 4
  • 18
  • 36
  • Note: As per the documentation of [`std::isalpha`](https://en.cppreference.com/w/cpp/string/byte/isalpha), the argument passed to `std::isalpha`, should first be converted to `unsigned char`, to avoid the possibility of UB. – Algirdas Preidžius May 29 '19 at 14:56
  • That is one way of doing it, but the documentation, itself, provides a cleaner looking example: `return std::count_if(s.begin(), s.end(), [](unsigned char c){ return std::isalpha(c); });` – Algirdas Preidžius May 29 '19 at 15:01
  • @AlgirdasPreidžius I don't think that's what the OP wants. He wants to delete non-alphas, not count alphas. – Paul Sanders May 29 '19 at 15:29
  • I just copy-pasted the relevant part of the example, in the documentation, that I linked to. I thought that my comment was clear about that. – Algirdas Preidžius May 29 '19 at 15:31