3

そのため、ファイルからすべての単語を読み取り、句読点を削除しようとしています。句読点を削除するロジックは次のとおりです。

編集:プログラムは実際には完全に実行を停止します。それを明確にしたいだけです

ifstream file("text.txt");

string              str;
string::iterator    cur;

for(file>>str; !file.eof(); file>>str){
    for(cur = str.begin(); cur != str.end(); cur++){
         if (!(isalnum(*cur))){
            cur = str.erase(cur);
         }
    }
cout << str << endl;
...
}

次のようなテキスト ファイルがあるとします。

This is a program. It has trouble with (non alphanumeric chars)

But it's my own and I love it...

このビットのロジックの直後に文字列を挿入すると、次のようになりますcoutendl;

This
is
a
program
It
has
trouble
with
non
alphanumeric

そしてそれはすべての人々です。イテレータのロジックに何か問題がありますか? どうすればこれを修正できますか?

ありがとうございました。

4

3 に答える 3

2

変換されたリストを作成するときに句読点をコピーないのはどうですか。わかった。おそらくやり過ぎ。

#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <cctype>
using namespace std;

// takes the file being processed as only command line param
int main(int argc, char *argv[])
{
    if (argc != 2)
        return EXIT_FAILURE;

    ifstream inf(argv[1]);
    vector<string> res;
    std::transform(istream_iterator<string>(inf),
        istream_iterator<string>(),
        back_inserter(res),
        [](const string& s) {
            string tmp; copy_if(s.begin(), s.end(), back_inserter(tmp),
            [](char c) { return std::isalnum(c); });
            return tmp;
        });

    // optional dump to output
    copy(res.begin(), res.end(), ostream_iterator<string>(cout, "\n"));

    return EXIT_SUCCESS;
}

入力

All the world's a stage,
And all the men and women merely players:
They have their exits and their entrances;
And one man in his time plays many parts,
His acts being seven ages. At first, the infant,
Mewling and puking in the nurse's arms.

出力

All
the
worlds
a
stage
And
all
the
men
and
women
merely
players
They
have
their
exits
and
their
entrances
And
one
man
in
his
time
plays
many
parts
His
acts
being
seven
ages
At
first
the
infant
Mewling
and
puking
in
the
nurses
arms
于 2013-04-09T05:28:40.463 に答える