0

我有这种格式的文本文件

 wins = 2
 Player
 10,45,23
 90,2,23

我必须将 10 45 23 存储到向量中并将其传递给函数,问题是它在第一行之后中断

    string csvLine;
int userInput;
ifstream  data("CWoutput.txt");
string line;
string str;
vector<string> listOfScores;
while(getline(data,line))
{
    stringstream  lineStream(line);
    string        cell;
    while(getline(lineStream,cell,'\n'))
    {
        if (cell.at(0) != 'w'  || cell.at(0) != 'P')
        { 
            while(getline(lineStream,cell,','))
            {
                cout<<line<<endl;

                listOfScores.push_back(cell);
            }
        }
    }
    vector<transaction> vectorScores= this->winner(listOfCells);
    bool hasWon= false;
    hasWon= this->validateRule2(vectorScores);
    if(hasWon== true)
    {
        return true;
    }
    else
    {
        return false;
    }
}
4

2 回答 2

0

在这份声明中while(getline(lineStream,cell,'\n'))

lineStream不包含该'\n'字符,因为它已被前一个getline( data, line)函数丢弃。

您的 while 循环可能会简化为:

while(getline(data,line))
{
    data.clear();
    if (line[0] != 'w'  && line[0] != 'P') {
      stringstream  lineStream(line);
      string        cell;
      while(getline(lineStream,cell,','))
      {
        cout<<line<<endl;

        listOfScores.push_back(cell);
      }
      vector<transaction> vectorScores= this->winner(listOfCells);
      bool hasWon= false;
      hasWon= this->validateRule2(vectorScores);
      return hasWon;
   }
}
于 2013-10-25T10:04:49.713 回答
0

为什么你linestaream在循环中使用?你通过调用得到整条线路getline(data,line)

所以你可以做

while(getline(data,line))
{


        if (line.at(0) != 'w'  || line.at(0) != 'P')
        { 
            std::vector<std::string> x = split(line, ',');
            listOfScores.insert(listOfScores.end(),x.begin(),x.end());
        }
}

您可以使用拆分功能:

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}


std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, elems);
    return elems;
}
于 2013-10-25T10:26:08.047 回答