0

我知道这篇文章以前是关于堆栈溢出的,我结合了各种教程;但为什么这段代码会导致执行错误 - 它确实编译。

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

1 回答 1

2

是的,很多次

    while ( leaderBoardFile.good() )
    {
        playerInfoVector.clear();
        getline (leaderBoardFile,line);

应该

    while ( getline (leaderBoardFile,line) )
    {
        playerInfoVector.clear();

令人难以置信的是,这个错误重复了多少次。您实际上在第二个 while 循环中做对了,那么为什么在第一个循环中错了呢?

不幸的是,有些教程也弄错了。

添加检查您的向量中确实有三个项目也是明智的。像这样的东西

        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);
于 2013-04-15T21:07:07.287 回答