为什么这个cin读卡住了?

and*_*and 3 c++ cin

我在我的程序中发现了一个失败,导致我无法为变量赋值addAntonymAnswer1.我已经尝试cin.clear()在声明之前运行以获取该内容阅读我的yes/no答案,但代码只是不会响应.

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

         cin.clear();

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

         // cin reading STUCK, why!?  
Run Code Online (Sandbox Code Playgroud)

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

运行程序的输入是:

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
Run Code Online (Sandbox Code Playgroud)
#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;
      }
Run Code Online (Sandbox Code Playgroud)

Joh*_*itb 14

cin.clear()不清除标准输入.它的作用是清除错误位,比如eofbit,failbit和其他人,将流进了良好的状态.也许你期望它清除它里面的任何东西?如果用户输入

yes no
Run Code Online (Sandbox Code Playgroud)

就在你和你之前

cin >> someStringVariable;
Run Code Online (Sandbox Code Playgroud)

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

 no
Run Code Online (Sandbox Code Playgroud)

然后,调用将clear清除所有处于活动状态的错误位.然后,你的

cin>>addAntonymAnswer1;
Run Code Online (Sandbox Code Playgroud)

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

cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Run Code Online (Sandbox Code Playgroud)

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


如果你有一个cin >>后跟a getline:cin将在其读取令牌之后留下任何空格(也是换行符),但是getline在它到达这样的换行符后将停止读取,则会出现另一个问题.我看到你clear几乎把所有东西都放了.所以我想在你需要的时候告诉你,什么时候不需要.排序多个时不需要它cin >>.假设你有缓冲区:"foo \nbar \n".然后你做以下的阅读

cin >> a; // 1
cin >> b; // 2
Run Code Online (Sandbox Code Playgroud)

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

getline(cin, a);
getline(cin, b);
Run Code Online (Sandbox Code Playgroud)

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

cin >> a;
getline(cin, b);
Run Code Online (Sandbox Code Playgroud)

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