C++如何在读取文件时忽略符号

C++ How can I ignore symbols when reading a file?

本文关键字:符号 文件 读取 C++      更新时间:2023-10-16

这是我当前读取的文件代码:

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();
}

如何让我的代码忽略符号(".';:!等),只输出/读取单词?目前它正在读取文章上的每个符号。example"测试。","they"

像现在一样读取"单词",但在打印"单词"之前,先从字符串中过滤掉不需要的字符。

C++有许多算法函数可以帮助你做到这一点。出于您的目的,您可以查看例如std::remove_if并执行类似的操作

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"
    }
}

如果您可以使用Boost.Iostrems,您可以为流编写自己的InputFilter。查看此处的详细信息http://www.boost.org/doc/libs/1_60_0/libs/iostreams/doc/tutorial/writing_filters.html