我想从 txt 文件中读取乐谱。分数将进入一个结构。
struct playerScore
{
char name[32];
int score, difficulty;
float time;
};
文本文件看起来像这样
赛斯 26.255 40 7
作为一行,其中每个项目后面都有一个制表符。 (姓名\t时间\t分数\t难度\n)
当我开始阅读文本时,我不知道如何告诉程序何时停止。分数文件可以是任意数量的行或分数条目。这是我尝试过的。
hs.open("scores.txt", ios_base::in);
hs.seekg(0, hs.beg);
if (hs.is_open())
{
int currpos = 0;
while (int(hs.tellg()) != int(hs.end));
{
hs>> inScore.name;
hs >> inScore.time;
hs >> inScore.score;
hs >> inScore.difficulty;
hs.ignore(INT_MAX, '\n');
AllScores.push_back(inScore);
currpos = (int)hs.tellg();
}
}
我正在尝试创建一个循环,将一行代码读入数据的临时结构,然后将该结构插入一个结构 vector 。然后用输入指针的当前位置更新 currpos 变量。但是,循环只是卡在条件上并卡住。
最佳答案
有多种方法可以做到这一点,但以下可能是您正在寻找的方法。声明一个自由运算符以提取玩家分数的单行定义:
std::istream& operator >>(std::istream& inf, playerScore& ps)
{
// read a single line.
std::string line;
if (std::getline(inf, line))
{
// use a string stream to parse line by line.
std::istringstream iss(line);
if (!(iss.getline(ps.name, sizeof(ps.name)/sizeof(*ps.name), '\t') &&
(iss >> ps.time >> ps.score >> ps.difficulty)))
{
// fails to parse a full record. set the top-stream fail-bit.
inf.setstate(std::ios::failbit);
}
}
return inf;
}
有了它,您的阅读代码现在可以执行此操作:
std::istream_iterator<playerScore> hs_it(hs), hs_eof;
std::vector<playerScore> scores(hs_it, hs_eof);
关于c++ - 从 txt 文件中读取。无法解析信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22523809/