0

我试图解析一个名为 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 // 三种),这意味着这个循环运行一次而不做任何事情。下一次运行,line 将等于 AH Ks Js AD Ac // 三种。知道为什么会这样吗?

4

1 回答 1

0

我想你忘了放很多代码(卡片定义等)。而且,据我所知,您在某些地方有几个多余的定义。

但是,我已经实现了您想要的(解析名为 FileName 的文本文件的能力,如下所示):

KD JD 6s 5s 3c // no rank (king high)
AH Ks Js AD Ac // three of a kind

假设输入文件流已使用文件名初始化:

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

这就是你想要的。;)

于 2013-03-10T02:56:46.997 回答