2

以下のコードは、単語のグループを に格納std::vectorし、ユーザーが指定した特定の単語がベクトルに格納されているすべての単語と比較して、ベクトルに出現する回数をカウントするためのものです。

std::cin >>以下のプログラムでは、コンソールは 2 番目に入力を求めません。

#include <iostream>
#include <ios>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;

int main(int argc, const char * argv[])
{
   cout<<"enter your words followed ny EOF"<<endl;
   vector<string> words;
   string x;
   typedef vector<string>::size_type vec_size;
   vec_size size;
   while (cin>>x) 
   {
     words.push_back(x);
   }
   size=words.size();
   cin.clear();

   //now compare
   cout<<"enter your word:"<<endl;
   string my_word;
   int count=0;

   cin>>my_word;              //didn't get any prompt in the console for this 'cin' 
   for (vec_size i=0; i<size; ++i) 
   {
      my_word==words[i]?(++count):(count=count);
   }
   cout<<"Your word appeared "<<count<<" times"<<endl;
   return 0;

}

私が得る最終的な出力は、「あなたの言葉は0回現れました」です。コードの問題は何ですか。どんな助けでも素晴らしいでしょう。

4

3 に答える 3

3

プログラムは、ファイルの終わりまで単語リストを読み取ります。つまり、端末で EOF 文字 ( Ctrl-DLinux ではCtrl-Z ReturnWindows) を入力できますが、その場合はどうでしょうか?

ストリームをリセットした後、端末は引き続き読み取りを行うと思います。しかし、プログラムがディスク ファイルやパイプなどから入力を取得している場合、望みはありません。ファイルの終わりは永遠です。

代わりに、ある種のセンチネルを使用するか、カウントを前に付けます。そうすれば、最初のループをリストの論理的な最後まで実行できます。そして、要約ロジック用の単語を読み取ることができます。

while (cin>>x  &&  x != '*')   // The word "*" ends the list of words
   {
     words.push_back(x);
   }
   size=words.size();

   //now compare
   cout<<"enter your word:"<<endl;
于 2012-06-19T06:16:16.950 に答える
2
while (cin>>x) 
{
    words.push_back(x);
}

ここでは、失敗するまで読んでいます。したがって、このループが終了すると、cin はエラー状態になります。エラー状態をクリアする必要があります。

cin.clear();
于 2012-06-19T06:12:15.757 に答える
1

http://www.cplusplus.com/forum/articles/6046/

例と考えられる問題としてこれを読んでください!!

于 2012-06-19T06:13:42.767 に答える