gpt4 book ai didi

C++ ifstream 失败,为什么这条线没有到达它应该去的地方?

转载 作者:行者123 更新时间:2023-11-28 01:13:39 25 4
gpt4 key购买 nike

我想让标有//THIS LINE SHOULD BE PRINTING 的行执行它的操作,即打印“同义词”和“反义词”之间的 int 值。

这是文本文件:

词典.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();

关于C++ ifstream 失败,为什么这条线没有到达它应该去的地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/456357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com