我知道这篇文章是在堆栈溢出之前发布的,我已经结合了各种教程;但为什么这段代码会导致执行错误 - 它会编译。
void leaderBoard::loadFromFile(void)
{
string line;
ifstream leaderBoardFile ("leaderboard.data");
vector<string> playerInfoVector;
if (leaderBoardFile.is_open())
{
while ( leaderBoardFile.good() )
{
playerInfoVector.clear();
getline (leaderBoardFile,line);
std::string input = line;
std::istringstream ss(input);
std::string token;
//cout << line << endl;
while(getline(ss, token, ',')) {
//for current line;
playerInfoVector.push_back(token);
}
string firstName = playerInfoVector.at(0);
string stringAge = playerInfoVector.at(1);
string stringScore = playerInfoVector.at(2);
//int age;
//stringstream(stringAge) >> age;
//int score;
//stringstream(stringScore) >> score;
//addScore(firstName,age,score);
////stringstream(stringAge) >> age;
////Add text to vector (push back)
playerInfoVector.clear();
}
leaderBoardFile.close();
}
else cout << "Unable to open file";
}
答案 0 :(得分:2)
是很多次
while ( leaderBoardFile.good() )
{
playerInfoVector.clear();
getline (leaderBoardFile,line);
应该是
while ( getline (leaderBoardFile,line) )
{
playerInfoVector.clear();
令人难以置信的是,这个错误重复了多少次。你实际上在你的第二个循环中得到了它,所以为什么第一个错误呢?
不幸的是,有些教程也会出错。
添加一个检查确实你的向量中确实有三个项目也是明智的。像这样的东西
if (playerInfoVector.size() < 3)
{
cerr << "Not enough items in player info vector\n";
exit(1);
}
string firstName = playerInfoVector.at(0);
string stringAge = playerInfoVector.at(1);
string stringScore = playerInfoVector.at(2);