C ++ ifstream 오류, 왜이 라인이 예상되는 곳으로 가지 않습니까?

StackOverflow https://stackoverflow.com/questions/456357

  •  19-08-2019
  •  | 
  •  

문제

//이 줄은 인쇄해야합니다.이 선은 "동의어"와 "antonyms"사이의 int 값을 인쇄하는 것입니다.

이것은 텍스트 파일입니다.

Dictionary.txt

1 cute
2 hello
3 ugly
4 easy
5 difficult
6 tired
7 beautiful
synonyms
1 7
7 1
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() {     
             }

             int id() const {return myId;}

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


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

             {

             stringstream synstream(synline);

             vector<int> synsAux;

             int num;

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

              for (int i=0; i<synsAux.size(); i++){
              cout<<synsAux[i]<<endl;  //THIS LINE SHOULD BE PRINTING

             }       



             }

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

             }

             //--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;}

             private:
                   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: ";
          getline (cin,wordFile);

          ifstream inStream (wordFile.data());

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

          }

          vector <WordInfo> wordVector; 

          WordInfo aword;



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

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




          vector <int> intVector;
          string aLine; //suspect


          // bad statement?
          while (getline(inStream, aLine)&&(aLine!=("antonyms"))){

                aword.pushSynonyms(aLine, wordVector);

                }




          system("PAUSE");

          return 0;
      }
도움이 되었습니까?

해결책

문제는 여기에있는 것 같습니다.

in>>myId>>word;

"동의어"에서는 추출을 줄입니다 myId 실패하고 세트 failbit 스트림에서 다음 추출이 실패하게됩니다. 스트림에서 추가 요소 ( "동의어"라는 단어)를 추출하기 전에 오류 제어 상태를 재설정해야합니다.

in.clear();

다른 팁

먼저 컴파일러 경고를 켭니다. 그것은 당신이 괜찮다고 생각하지만 실제로는 그렇지 않은 것을 찾는 데 도움이 될 수 있습니다. 예를 들어, 비의 기능void 반환 유형은 항상 무언가를 반환해야합니다. 그렇지 않으면 프로그램의 행동이 정의되지 않으며 정의되지 않은 행동에는 "프로그램의 나중에 미묘한 차이를 제외하고는 원하는대로 정확하게 작동합니다"가 포함됩니다. G ++를 사용하는 경우 경고 옵션은 다음과 같습니다. -Wall.

둘째, 실행되지 않는 강조 표시된 라인만이 아닙니다. 그만큼 전체 pushSynonyms 기능 결코 전화를받지 않습니다. 수업이 아직 디버거를 사용하는 방법을 다루었습니까? 그렇다면 사용하는 것을 고려하십시오. 그렇지 않다면 몇 가지를 넣으십시오.cout"프로그램의 진술은 프로그램이 잘못되기 전에 얼마나 멀리 떨어져 있는지 확인할 수 있습니다.

셋째, 스트림 읽기 실패가 발생하면 스트림의 실패 비트가 설정됩니다. 당신이 그것을 지울 때까지 (STH의 답변에서 볼 수 있듯이), 더 이상 추출이 해당 스트림에서 발생할 수 없으므로 모든 추가 사용 >> 그리고 getline 실패합니다.

진단 인쇄를 한 적이 있습니까? 예를 들어, 무엇입니까 synsAux.size()? 당신은 무엇이 있는지 확인 했습니까? synline 처리를 시작하기 전에? 입력 스트림에서 수집되는 숫자를 확인 했습니까?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top