【问题标题】:c++ read from file skip certain linesc++ 从文件中读取跳过某些行
【发布时间】:2013-10-25 09:59:27
【问题描述】:

我有这种格式的文本文件

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

【问题讨论】:

  • 除此之外,请将if (hasWon== true) { return true; } else { return false; }替换为return hasWon;
  • 可以,或者直接return this-&gt;validateRule2(vectorScores)
  • return this-&gt;validateRule2(this-&gt;winner(listOfCells))

标签: c++ file csv


【解决方案1】:

为什么你在循环中使用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;
}

【讨论】:

    【解决方案2】:

    在此声明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;
       }
    }
    

    【讨论】:

    • 它不会进入下一行
    猜你喜欢
    • 2012-10-09
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多