基本上,我想从文件中读取高分,并检查用户是否在记分板上获得了足够的分数。我试着这样做:
string initials[10];
int scores[10];
//load txt
ifstream highscores("highscores.txt");
if(highscores.is_open())
{
while(highscores.good())
{
for(int x=0;x<10;x++)
{
getline(highscores,initials[x],' ');
highscores >> scores[x];
}
}
}首字母的长度只有3个字符,所以我可以实现一个2dim。数组,但我想用字符串来尝试它。它显示我生成了一个大小为10的字符串,我该如何编写它才能使用10个数组而不是1个数组?(我知道我可以从array1中将它们命名为10个数组。到10,循环遍历它们听起来要好得多。高分文件只是一组10个缩写的AAA,BBB等和一些分数。
Highscores.txt示例:
AAA 5000
BBB 4000
CCC 3000发布于 2011-12-10 21:00:23
使用std::map保存首字母和相关分数。例如:
int main()
{
// Map is keyed by initials.
std::map<std::string, int> scores;
std::ifstream in("highscores.txt");
if (in.is_open())
{
for (;;)
{
std::string line;
std::getline(in, line);
if (!in.good())
{
break;
}
const size_t space_idx = line.find(' ');
if (std::string::npos != space_idx)
{
// The initials are everthing before the space.
// Score everything after the space.
scores[line.substr(0, space_idx)] =
atoi(line.substr(space_idx + 1).c_str());
}
}
in.close();
}
// Check who has achieved required score.
for (std::map<std::string, int>::iterator i = scores.begin();
i != scores.end();
i++)
{
if (i->second > 3500)
{
std::cout << i->first << "\n";
}
}
return 0;
}https://stackoverflow.com/questions/8456581
复制相似问题