У меня есть текстовый файл в этом формате
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;
}
}
Почему вы используете 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());
}
}
и вы можете использовать функции split:
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;
}
В этом выражении 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;
}
}
if (hasWon== true) { return true; } else { return false; }
сreturn hasWon;
,return this->validateRule2(vectorScores)