1

これまでの私のコードは次のとおりです

int main()
{
string word;
int wordcount = 0;
cout << "Enter a word to be counted in a file: ";
cin >> word;
string s;
ifstream file ("Names.txt");
while (file >> s)
        {
            if(s == word)
            ++ wordcount;
        }
int cnt = count( istream_iterator<string>(file), istream_iterator<string>(), word());
cout << cnt << endl;
}

ファイル Names.txt には、大量の単語と数字が含まれています。istream iterator が単語をカウントする方法はよくわかりませんが、いくつかの結果が得られました。現時点で唯一のエラーは

in function int main 
error: no match for call to `(std::string) ()'

それは「int cnt」で始まる行で発生します。数時間試してみましたが、C++ にはあまり詳しくありません。余分な文字列を作成するか、単語文字列を何らかの方法で変更する必要があるようです。

助けていただければ幸いです!!

4

3 に答える 3

1

この行は正しくありません:

 int cnt = count( istream_iterator<string>(infile), 
            istream_iterator<string>(), word());
                                          //^^^^^Error

次のようにする必要があります。

int cnt = count( istream_iterator<string>(infile), 
                istream_iterator<string>(), word);

その間、次の部分を削除します。

while (infile >> s)
{
    if(s == word)
    ++ wordcount;
}

それ以外の場合、fileカウントアルゴリズムでイテレータを使用すると、ファイルの最後がポイントされます。両方を同時に使用するのではなく、ループまたは反復子のいずれかを使用する必要があります。

于 2013-04-07T14:48:28.860 に答える
0

問題は、word() です。std::string で operator() を呼び出そうとしていますが、std::string にそのようなメンバー関数はありません。

ステートメントを次のように変更します。

int cnt = count(istream_iterator<string>(file), istream_iterator<string>(), word);
于 2013-04-07T14:51:21.180 に答える