3

我在我的程序中挑出了一个失败,它阻止我为变量赋值addAntonymAnswer1。我已经尝试cin.clear()在声明之前运行以让事情阅读我的yes/no答案,但代码不会响应。

失败的程序位位于内部void dictionaryMenu(vector <WordInfo> &wordInfoVector)并读取

         cin.clear();

         cout<<">";
         cin>>addAntonymAnswer1;

         // cin reading STUCK, why!?  

要到达程序的那个点,用户必须选择添加一个词,然后添加一个同义词。

运行程序的输入是:

dictionary.txt
1 cute
2 hello
3 ugly
4 easy
5 difficult
6 tired
7 beautiful
synonyms
1 7
7 1
3 2
antonyms
1 3
3 1 7
4 5
5 4
7 3

#include <iostream>
#include <fstream>
#include <string>

#include <sstream>
#include <vector>


using namespace std;



class WordInfo{

      public:

             WordInfo(){}

             WordInfo(string newWord){
                           word=newWord;                
             }

             ~WordInfo() { }

             int id() const {return myId;}

             void readWords(istream &in)
             {
               in>>myId>>word;     
             }

             vector <int> & getSynonyms () {

                    return mySynonyms;
             }

            vector <int> & getAntonyms() {

                     return myAntonyms;
            }

            string getWord() {
                     return word;
                   }


          void dictionaryMenu (vector <WordInfo> &wordInfoVector){

          cout<<endl<<"Would you like to add a word?"<<endl;   
          cout<<"(yes/no)"<<endl;
          cout<<">";
          string addWordAnswer;
          cin>>addWordAnswer;

          if (addWordAnswer=="yes")
          // case if the guy wants to add a word
          {
          cout<<endl;                  
          cout<<"Please, write the word "<<endl;                  

          string newWord;
          cout<<">";
          cin>>newWord;
          cout<<endl;         

          WordInfo newWordInfo (newWord);

          int newWordId = wordInfoVector.size() +1;

          newWordInfo.myId=newWordId;

          cout<<"The id of "<<newWordInfo.word<<" is "<<newWordInfo.myId<<endl<<endl; 

          wordInfoVector.push_back(newWordInfo);


          cout<<"Would you like to define which words on the existing dictionary are" <<endl 
          <<"synonyms of "<<newWordInfo.word<<"?"<<endl;


          cout<<"(yes/no)"<<endl;

          string addSynonymAnswer, addAntonymAnswer1, addAntonymAnswer2;
          cout<<">";
          cin>>addSynonymAnswer;  




          if (addSynonymAnswer=="yes")
          {

            cout<<endl;
            cout<<"Please write on a single line the ids for the synonyms of "
            <<newWordInfo.word<<endl<<"starting with its id, which is "<<newWordInfo.myId<<endl<<endl;

            cout<<"For example, to define that the synonym of the word 'cute', which has an id 1, is" 
            <<"'beautiful', which has an id 7, you should write: 1 7"<<endl<<endl;

            cout<<"In the case of "<<newWordInfo.word<<" you should start with "<<newWordInfo.myId<<endl;

            cin.clear();
            string lineOfSyns;
            cout<<">";

            cin>>lineOfSyns;

            newWordInfo.pushSynonyms(lineOfSyns, wordInfoVector); 

            cin.clear();     


                 cout<<"Would you like to define which words on the existing dictionary are" <<endl 
                 <<"antonyms of "<<newWordInfo.word<<"?"<<endl; 

                  //##HERE THE CIN READING OF addAntonymAnswer1 FAILS, WHY?

                 cin.clear();
                 cout<<">";
                 cin>>addAntonymAnswer1;

                 // cin reading STUCK, why!?   


                 if (addAntonymAnswer1=="yes"){ }                        

                    else if (addAntonymAnswer1=="no"){
                         // END DICTIONARY MENU
                         }                  
          }
             else if (addSynonymAnswer=="no"){

                cout<<"Would you like to define which words on the existing dictionary are" <<endl 
                 <<"antonyms of "<<newWordInfo.word<<"?"<<endl; 


                 cout<<">";
                 cin>>addAntonymAnswer2;

                 if (addAntonymAnswer2=="yes"){ }                        

                    else if (addAntonymAnswer2=="no"){
                         // END DICTIONARY MENU
                         }  

             }


          } // if addWordAnswer == "no"

          else if (addWordAnswer=="no"){

               // ######RETURN TO MAIN MENU############
               }        






            }

             void pushSynonyms (string synline, vector<WordInfo> &wordInfoVector){


             stringstream synstream(synline);

             vector<int> synsAux;

             // synsAux tiene la línea de sinónimos

             int num;

             while (synstream >> num) {synsAux.push_back(num);}

             int wordInfoVectorIndex;

             int synsAuxCopyIndex;



             if (synsAux.size()>=2){ // takes away the runtime Error



             for (wordInfoVectorIndex=0; wordInfoVectorIndex <wordInfoVector.size(); wordInfoVectorIndex++)
             {


                 if (synsAux[0]==wordInfoVector[wordInfoVectorIndex].id()){


                    // this is the line that's generating a Runtime Error, Why?                                                       
                    for (synsAuxCopyIndex=1; synsAuxCopyIndex<synsAux.size(); synsAuxCopyIndex++){

                    // won't run yet    
                    wordInfoVector[wordInfoVectorIndex].mySynonyms.push_back(synsAux[synsAuxCopyIndex]);      
                        }                                                          
                 }     
             } 

             }// end if size()>=2


            } // end pushSynonyms








             void pushAntonyms (string antline, vector <WordInfo> &wordInfoVector)
             {



             stringstream antstream(antline);

             vector<int> antsAux;

             int num;

             while (antstream >> num) antsAux.push_back(num);


             int wordInfoVectorIndex;

             int antsAuxCopyIndex;   



             if (antsAux.size()>=2){ // takes away the runtime Error             

             for (wordInfoVectorIndex=0; wordInfoVectorIndex <wordInfoVector.size(); wordInfoVectorIndex++)
             {


                 if (antsAux[0]==wordInfoVector[wordInfoVectorIndex].id()){


                    // this is the line that's generating a Runtime Error, Why?                                                       
                    for (antsAuxCopyIndex=1; antsAuxCopyIndex<antsAux.size(); antsAuxCopyIndex++){

                    // won't run yet    
                    wordInfoVector[wordInfoVectorIndex].myAntonyms.push_back(antsAux[antsAuxCopyIndex]);      
                        }                                                          
                 }     
             } 

             }// end if size()>=2





             }

             //--dictionary output function

             void printWords (ostream &out)
             {
                out<<myId<< " "<<word;     
             }



             //--equals operator for String
             bool operator == (const string &aString)const
             {
                           return word ==aString; 

             }


             //--less than operator

             bool operator <(const WordInfo &otherWordInfo) const
             { return word<otherWordInfo.word;}

             //--more than operator

             bool operator > (const WordInfo &otherWordInfo)const
             {return word>otherWordInfo.word;}

             public: 

                  vector<int> mySynonyms;
                  vector <int> myAntonyms;


                   string word;
                   int myId;


      };

      //--Definition of input operator for WordInfo
      istream & operator >>(istream &in, WordInfo &word)
      {
         word.readWords(in); 

      }



      //--Definition of output operator

      ostream & operator <<(ostream &out, WordInfo &word)
      {
            word.printWords(out);  

      }





      int main() {

          string wordFile;
          cout<<"enter name of dictionary file: "<<endl;
          getline (cin,wordFile);

          ifstream inStream (wordFile.data());

          if(!inStream.is_open())
          {
          cerr<<"cannot open "<<wordFile<<endl; 
          exit(1);                      

          }

          vector <WordInfo> wordInfoVector; 

          WordInfo aword;





          while (inStream >>aword && (!(aword=="synonyms")))
          {
              wordInfoVector.push_back(aword);


          }

          inStream.clear();









          vector <int> intVector;
          string synLine; 






          while (getline(inStream, synLine)&&(synLine!=("antonyms"))){

                aword.pushSynonyms(synLine, wordInfoVector);

                }



          int theIndex;



          string antLine;

          while (getline(inStream,antLine)){

                aword.pushAntonyms(antLine, wordInfoVector);
                }      



          cout<<endl<<"the words on the dictionary are: "<<endl;

          int h=0;          
          while (h<wordInfoVector.size()){
                cout<<wordInfoVector[h]<<endl;
                h++;
                }

          aword.dictionaryMenu(wordInfoVector);

          system("PAUSE");

          return 0;
      }
4

4 回答 4

14

cin.clear()不清除标准输入。它所做的是清除错误位,例如eofbitfailbit其他,并将流设置为良好状态。也许您希望它可以清除其中的任何内容?如果用户键入

yes no

就在之前,还有你

cin >> someStringVariable;

它将读取到no并且流仍将包含

 no

调用clearthen 会清除所有处于活动状态的错误位。那么,你的

cin>>addAntonymAnswer1;

将读取no前一次读取未吃掉的内容,并且该操作立即返回,而不是等待新的输入。你应该做的是做一个clear然后忽略,直到下一个换行符。你告诉它它应该最大程度地忽略的字符数量。该金额应该是可能的最高数字:

cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

这样做会使流为空,随后的读取将等待您输入内容。


如果您有 acin >>后跟 a ,则会出现另一个问题getline: cin 将在其读取标记之后留下任何空格(也是换行符),但getline在遇到这样的换行符后将停止读取。我看到你clear几乎把所有事情都放在了后面。所以我想告诉你什么时候需要,什么时候不需要。当您对多个cin >>. 假设您的缓冲区中有:“foo\nbar\n”。然后你做以下阅读

cin >> a; // 1
cin >> b; // 2

在第一个之后,您的缓冲区将包含“\nbar\n”。也就是说,换行符仍在。第二个cin>>将首先跳过所有空格和换行符,以便它可以应对\nbar. 现在,您还可以对多个getline调用进行排序:

getline(cin, a);
getline(cin, b);

Getline 将丢弃\n它在行尾读取的内容,但不会忽略开头的换行符或空格。因此,在第一个 getline 之后,缓冲区包含“bar\n”。第二个 getline 也将正确读取“bar\n”。现在,让我们考虑需要清除/忽略的情况:

cin >> a;
getline(cin, b);

第一个会将流保留为“\nbar\n”。然后 getline 将立即看到\n开头的 ,并认为它读取的是空行。因此,它将立即继续而不等待任何内容,将流保留为“bar\n”。所以,如果你有一个getlineafter acin>>你应该首先执行 clear/ignore 序列,以清除换行符。但是在getlineor之间cin>>,你不应该这样做。

于 2009-01-25T21:25:45.580 回答
1

它“卡住”了,因为它正在等待输入。cin 附加到程序的标准输入句柄,您必须输入一些内容并按 Enter。

于 2009-01-25T20:55:49.197 回答
1

cin >> ...从标准输入读取,直到找到空白字符。例如,当您输入8 5同义词列表时,8就会被读入lineOfSyns,仅此而已。当程序到达cin >> addAntonymAnswer1时,5被读入addAntonymsAnswer1。您的程序行为异常,因为它期望yesno但它得到了5.

看看 usingcin.getline()而不是>>. 例如,参见 本页第 18.2 和 18.3 节。

于 2009-01-25T21:39:07.910 回答
1

在您的程序中,您询问用户:

Please write on a single line the ids for the synonyms of test
starting with its id, which is 8

For example, to define that the synonym of the word 'cute', which has an id 1, i
s'beautiful', which has an id 7, you should write: 1 7

In the case of test you should start with 8

然后您尝试在用户键入的行中读取

cin>>lineOfSyns;

但是,这只读取到第一个空格。因此,当用户输入的第二个数字仍然在cin缓冲区中时

cin>>addAntonymAnswer1;

行被执行,以便将数据读入addAntonymAnswer1字符串。用户永远没有机会输入“是”或“否”,并且您对这些值的测试失败。

您应该考虑更改为使用string重载 forgetline()进行读取:

getline( cin, stringvar);

这可能比 using 更好cin.getline(),因为它没有需要的重载string- 使用该成员函数,您需要读入一个字符数组,这远不如读入一个string.

于 2009-01-25T21:42:59.133 回答