我尝试解析一个名为FileName的文本文件,如下所示:
KD JD 6s 5s 3c // no rank (king high)
AH Ks Js AD Ac // three of a kind现在我想将它们存储到一个向量中(“//”之前的所有内容)。
int FileParsing(vector<Card> & v, char * FileName) {
ifstream ifs;
ifs.open(FileName);
if (!ifs.is_open()){
cout << "file cannot be opened." << endl;
} else {
string line;
while(getline(ifs, line)){
istringstream iss (line);
bool condition = CountWords(line); //dont worry about this method
ReadCardDefinitionStrings (condition, line, v);
}
}
return 0;
}
void ReadCardDefinitionStrings (bool condition, string line, vector<Card> & v){
istringstream iss (line);
string CardDefinitionStrings; //e.g. 2C, 3h, 7s, Kh
if (condition) {
while(iss>>CardDefinitionStrings){
if (CardDefinitionStrings == "//"){ //stop reading after it sees "//"
return;
}
Card c = TestCard(CardDefinitionStrings);
v.push_back(c);
}
}
}我遇到的问题是:当它在3c之后看到"//“时,它会返回到
while(getline(ifs, line)){
istringstream iss (line);
bool condition = CountWords(line);
ReadCardDefinitionStrings (condition, line, v);
}但这一次,行是空的(我希望它是: AH Ks Js AD Ac // three of a Ks),这意味着这个循环只运行一次,不做任何事情。下一次运行时,行等于AH,Ks,Js,AD,Ac //三种类型。知道为什么会这样吗?
发布于 2013-03-10 10:56:47
我想你忘了写很多代码了(卡片定义之类的)。而且,据我所知,在某些地方有几个多余的定义。
但是,我已经实现了您想要的功能(能够解析一个名为FileName的文本文件,如下所示):
KD JD 6s 5s 3c // no rank (king high)
AH Ks Js AD Ac // three of a kind假设已经使用Filename初始化了输入文件流:
ifstream ifs(FileName);
if (!ifs.is_open()) {
cout << "file cannot be opened." << endl;
}
else {
string line;
//getline reads up until the newline character
//but you want the characters up to "//"
while(std::getline(ifs, line)) {
//line has been read, now get rid of the "//"
string substr = line.substr(0,line.find("//"));
//assign the substr to an input stringstream
istringstream iss(substr);
//this will hold your card
//NOTE: Since I don't have your implementation of Card, I put it as a string instead for demonstration purposes
string card;
//keep reading until you've read all the cards in the substring (from line)
while (iss >> card) {
v.push_back(card);//store the card in the vector
cout << card << endl;//now output it to verify that the cards were read properly
}
cout << endl;//this is just for spacing - so it'll help us distinguish cards from different lines (in the output)
}
ifs.close();
}输出:
KD
JD
6s
5s
3c
AH
Ks
Js
AD
Ac这就是你想要的。;)
https://stackoverflow.com/questions/15318190
复制相似问题