gpt4 book ai didi

C++读取txt文件的CSV值

转载 作者:行者123 更新时间:2023-11-28 03:18:57 25 4
gpt4 key购买 nike

我知道这个帖子以前在stack overflow上发过,综合了各种教程;但为什么这段代码会导致执行错误 - 它确实可以编译。

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

最佳答案

是的很多次

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

应该是

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

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

不幸的是,一些教程也犯了这个错误。

添加一个检查以确保您的 vector 中确实包含三个项目也是明智的。像这样

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

关于C++读取txt文件的CSV值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16024653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com